首页 > 解决方案 > Vue2:包含/注入全局实用程序类的正确方法

问题描述

我有 Vue.js 项目,我想在其中使用实用程序类来实现我想在所有模块中使用的功能。

模块/Utils.js

export default class Utils {
    array_count (arr) {
        return Array.isArray(arr) ? arr.length : 0;
    }
}

main.js

import Vue from 'vue';
import Utils from 'modules/Utils';
export default new Vue({
    el: '#app',
    router,
    template: '<App/>',
    components: {
        App
    },
    utils: Utils // this has no affect?

});

模块/some.js

import Vue from 'vue';
import Utils from 'modules/Utils'; // I don't want this
var utils = new Utils;             // I don't want this
console.log(utils.array_count(['a','b','c']));

我真的不明白如何注入 Utils 类。上面的例子有效 - 但我想摆脱每个模块中 Class 的导入。我想当我将它作为依赖项添加到 main.js 中时,我应该能够在我的项目中的任何地方调用它。

标签: dependency-injectionvuejs2

解决方案


当您想从每个组件访问帮助程序时,您可以注册一个全局 mixin。改变你Utils.js的看起来像一个Mixin

export default {
    methods: {
        array_count (arr) {
            return Array.isArray(arr) ? arr.length : 0;
        }
    }
}

然后,导入 mixin 并全局添加。

import Vue from 'vue';
import Utils from 'modules/Utils';
Vue.mixin(Utils);
export default new Vue({
    el: '#app',
    router,
    template: '<App/>',
    components: {
        App
    },

或者,如果您希望某些辅助函数在全局范围内不可用,而仅在某些组件中可用,则可以导入 mixin 并将其手动添加到 Vue 组件中。


推荐阅读