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

我可以通过在 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)

  }

})


胡子哥哥
浏览 97回答 2
2回答

长风秋雁

您正在尝试导出两个默认值。默认值意味着您只需说即可获得该值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 指南:编写一个插件,我们可以按照该指南开发我们的指令,然后允许用户通过第二个参数=激活特定指令options。就像下面的演示(假设 export myDirectives,并且只 enable 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 2Vue.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>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript