Vue.js - 将自定义指令导入为 ES6 模块

问题描述 投票:0回答:1

我有一个相当具体的问题。

我通过rails webpacker在我的rails应用程序中使用vue,要使用vue组件,我必须在我的布局中放置一个javascript包标签,并引用一个javascript文件,该文件反过来渲染vue组件,你可以想象总共这种方法让我做了很多变通办法,但我还剩下的一件事是一个 vue 自定义指令

click-outside
,我必须将其添加到我的每个 vue 组件生成器中,例如,在
filter-products.js

import Vue from "vue";
import filterProducts from "../../views/filter-products";
var element = document.getElementById("filter-products");
const props = JSON.parse(element.getAttribute("props"));

Vue.directive('click-outside', {
    bind: function(el, binding, vNode) {
    //bind logic
    },

    unbind: function(el, binding) {
    //unbind logic
    }
});

if (element != null) {
  new Vue({
    render: (h) => h(filterProducts, { props }),
  }).$mount(element);
}

自定义指令代码实际上很大,所以我想到但不确定该怎么做是两件事之一:

  • 在 ES6 模块中拥有该自定义指令的大量内容并在此处导入并直接使用它。
  • 为包含此自定义指令的 Vue 创建一个原型并导入它,而不是导入
    vue from "vue"

这两种方法哪个更好?我将如何实现它们?谢谢!

javascript vue.js vuejs2 vue-component
1个回答
2
投票

创建一个名为

directives
的文件夹,并为每个指令创建一个文件,以使您的代码更有组织性和可维护性,尤其是在团队中:

import Vue from 'vue';

const directiveName = {
    inserted: function(el, binding) {},
    update: function(el, binding) {},
};

export default directiveName;
Vue.directive('directiveName', directiveName);//optional

然后将其导入任何组件中,例如:

import directiveName from 'path-to-directives-folder/directives/directiveName'

然后按如下方式使用它:

data(){
  ...
},
directives:{directiveName}
© www.soinside.com 2019 - 2024. All rights reserved.