假设我有以下情况,使用Global Mixin使用Vue创建全局辅助方法:
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”,但不断返回“undefined”。
我认为这个代码是您正在寻找的:
var mixin = {
methods: {
foo: function () {
console.log('foo')
},
conflicting: function () {
console.log('from mixin')
}
}
}
var vm = new Vue({
mixins: [mixin],
methods: {
bar: function () {
console.log('bar')
},
conflicting: function () {
console.log('from self')
}
}
})
vm.foo() // => "foo"
vm.bar() // => "bar"
vm.conflicting() // => "from self"
来自docs