首页 > 解决方案 > 如何使用 Vue 实例中的 Global Mixin 方法

问题描述

假设我有以下情况,使用一个 Global Mixin 用 Vue 创建一个全局 helper 方法:

import Vue from "vue";

Vue.mixin({
    methods: {
        replaceString: function (word) {
            return word.toLowerCase().replace(/\W/g, '');
        }
    }
});

let vm = new Vue({
    methods: {
        doSomething: function() {
             console.log(this.replaceString('Hello World'); //helloword
        }
    }
});

我知道我可以在组件及其子组件内部的其他方法中调用该方法。但是如何从 Vue 实例“vm”中调用 mixin 方法“replaceString”呢?我尝试使用“vm.replaceString”,但一直返回“未定义”。

标签: javascriptvue.jsvuejs2vue-mixin

解决方案


对您的代码几乎没有更改,并且可以正常工作:

  1. 您应该更改 mixin 的定义(var mixin 而不是 Vue.mixin)
  2. 将 mixin 导入新的 vue 组件(mixins = [mixin])

    import Vue from "vue";
    
    var mixin = {
        methods: {
            replaceString: function (word) {
                return word.toLowerCase().replace(/\W/g, '');
            }
        }
    };
    
    let vm = new Vue({
        mixins: [mixin]
        methods: {
            doSomething: function() {
                console.log(this.replaceString('Hello World'); //helloword
            }
        }
    });
    

推荐阅读