如何创建具有多个 vue 指令的 npm 包?或者我应该为每个指令创建一个包?

How to create a npm package with multiple vue directives? Or should I create one package per directive?

我可以通过在 src/index.js 文件中导出单个 vue 指令来创建 npm 包。但是我怎样才能创建一个让你使用多个 vue 指令的包。我无法在同一个 index.js 文件中导出两个 vue 指令。

export default Vue.directive('directive1', {
  inserted: function (el, binding, vnode) {
    el.addEventListener('mouseup', (e) => mouseup(e, el, _data))
    el.addEventListener('mousedown', (e) => mousedown(e, el, _data))
    el.addEventListener('mousemove', (e) => mousemove(e, el, _data))
    setDraggerOffset(el, _data)
  }
})

export default Vue.directive('directive2', {
  inserted: function (el, binding, vnode) {
    el.addEventListener('mouseup', (e) => mouseup(e, el, _data))
    el.addEventListener('mousedown', (e) => mousedown(e, el, _data))
    el.addEventListener('mousemove', (e) => mousemove(e, el, _data))
    setDraggerOffset(el, _data)
  }
})

您正在尝试导出两个默认值。默认值意味着您只需说 import MyPack from 'path/to/package' 即可获得该值。您需要导出常量,并在导入的位置进行解构。

包中

export const vD1 = Vue.directive('directive1', {
  ...
})

export const vD2 = Vue.directive('directive2', {
  ...
})

无论您在何处导入:

import { vD1, vD2 } from 'path/to/package';

选中Vue Guide: Writing one plugin,我们可以按照这个指南来开发我们的指令,然后允许用户通过第二个参数激活特定的指令=options.

像下面的演示(假设导出 myDirectives,并且只启用 directive1):

let myDirectives = {}
let _defaultDirectives = ['directive1', 'directive2']
myDirectives.directive1 = {
  inserted: function (el, binding, vnode) {
    el.addEventListener('mouseup', (e) => mouseup(e, el, _data))
    el.addEventListener('mousedown', (e) => mousedown(e, el, _data))
    el.addEventListener('mousemove', (e) => mousemove(e, el, _data))
    console.log('directive1', `setDraggerOffset(el, _data)`)
  }
}

myDirectives.directive2 = {
  inserted: function (el, binding, vnode) {
    el.addEventListener('mouseup', (e) => mouseup(e, el, _data))
    el.addEventListener('mousedown', (e) => mousedown(e, el, _data))
    el.addEventListener('mousemove', (e) => mousemove(e, el, _data))
    console.log('directive2', `setDraggerOffset(el, _data)`)
  }
}

myDirectives.install = function (Vue, options) {
  let selectedDirectives = (options && options.directives) || _defaultDirectives
  selectedDirectives.forEach((directive) => 
    Vue.directive(directive, this[directive])
    // this[directive + 'Definition'] = Vue.directive(directive, this[directive])
  )
}

// export default myDirectives

// Vue.use(myDirectives) // default option is register both directive1 and directive 2
Vue.use(myDirectives, {directives: ['directive1'] }) // register directive1 only

// console.log('Definition', myDirectives.directive1Definition, myDirectives.directive2Definition)

new Vue({
  el: '#app'
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <span v-directive1></span>
  <span v-directive2></span>
</div>