[英]How can I use a Global Mixin method from a Vue instance
Let's suppose that I have the following situation, using a Global Mixin to create a global helper method with Vue:假设我有以下情况,使用一个 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
}
}
});
I know that I can invoke the method inside the other methods, inside of the component and their childs.我知道我可以在组件及其子组件内部的其他方法中调用该方法。 But how can I invoke the mixin method "replaceString" from the Vue instance "vm"?
但是如何从 Vue 实例“vm”中调用 mixin 方法“replaceString”呢? I tried to use "vm.replaceString", but keeps returning "undefined".
我尝试使用“vm.replaceString”,但一直返回“未定义”。
Few changes to your code and it works:对您的代码几乎没有更改,并且可以正常工作:
Import the mixin to your new vue component (mixins = [mixin])将 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 } } });
I think this chunk o code is what you are looking for:我认为这个代码块是你正在寻找的:
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"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.