我无法从组件调用mixin方法,我收到此错误this.hello is not a function
。
我可以从Vue实例中调用hello()
,但我不能在组件中调用它。
什么事??
<div id='vue-app'>
<cmp></cmp>
</div>
const mixin = {
methods: {
hello() {
return 'Hello World!';
}
},
created() {
console.log('Mixin Created!');
},
};
const cmp = {
created() {
console.log('From Cmp:', this.hello());
},
};
new Vue({
components: {
cmp
},
el: '#vue-app',
mixins: [mixin],
created() {
console.log('From VM:', this.hello());
},
});
答案 0 :(得分:3)
正确,mixin方法/数据仅在其添加的实例中可用。但是,如果你真的想在你的root实例中使用mixin,你可以从根实例的任何子组件调用this.$root.hello()
答案 1 :(得分:2)
好吧,似乎我必须在整个Component实例中加载Mixin,而不是从Vue父实例加载:)
答案 2 :(得分:0)
如果将nuxt与vue一起使用,则@daxigu将不起作用,因为$root
是nuxt本身。我能做什么?这个:
this.$root.$children[1].myRootMethod()
$ root::正如我之前说的,这是nuxt。
$ children [0]:正在加载。
$ children [1]::是您的主要组件,在我的情况下,它是具有一些全局组件和全局mixin的基本布局。
希望有帮助。