Let's suppose that I have the following situation, using a Global Mixin to create a global helper method with 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
}
}
});
I know that I can invoke the method inside the other methods, inside of the ponent and their childs. But how can I invoke the mixin method "replaceString" from the Vue instance "vm"? I tried to use "vm.replaceString", but keeps returning "undefined".
Let's suppose that I have the following situation, using a Global Mixin to create a global helper method with 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
}
}
});
I know that I can invoke the method inside the other methods, inside of the ponent and their childs. But how can I invoke the mixin method "replaceString" from the Vue instance "vm"? I tried to use "vm.replaceString", but keeps returning "undefined".
Share Improve this question asked Feb 15, 2019 at 19:18 Marcelo RodovalhoMarcelo Rodovalho 9331 gold badge16 silver badges27 bronze badges 1- It says at docs that you can transform it into a ponent, so you would just import it and use. Take a look at the docs: vuejs/v2/guide/mixins.html – Marco Commented Feb 15, 2019 at 20:28
2 Answers
Reset to default 2Few changes to your code and it works:
- You should change the definition of your mixin (var mixin instead of Vue.mixin)
Import the mixin to your new vue ponent (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"
From the docs
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745331355a4622892.html
评论列表(0条)