【问题标题】:Vue.js -Importing custom directive as ES6 ModuleVue.js - 将自定义指令导入为 ES6 模块
【发布时间】:2023-03-22 02:04:02
【问题描述】:

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

我通过rails webpacker在我的rails应用程序中使用vue,要使用vue组件,我必须在我的布局中放置一个javascript包标签,并引用一个javascript文件,该文件反过来呈现vue组件,你可以想象总的来说,这种方法让我做了很多变通办法,但我还剩下一件事是一个 vue 自定义指令 click-outside,我必须将它添加到我的每个 vue 组件生成器中,例如,在 @ 987654322@

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】:

    创建一个名为 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}
    

    【讨论】:

    • 谢谢!但是,我想在我的问题中执行 new Vue() 的部分使用它,这可能吗?
    • 工作正常,只是将用法改为Vue.directive("click-outside", clickOutside);
    • 其中clickOutside是导入的文件名
    • directiveName 只是一个示例,该指令可以导入到您的 vue 应用程序的任何位置(main.js 和组件
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-18
    • 2019-01-10
    • 2020-03-31
    • 2020-09-05
    • 2020-08-24
    • 1970-01-01
    • 2019-01-05
    相关资源
    最近更新 更多