我想实现将this.$store.value
分配给本地数据的这种逻辑。例如,这就是我在pages / index.vue中所做的。
method: {
this.value = this.$store.value
}
我想把它写成mixins,因为实际上我周围还有其他逻辑,而且我使用了一些页面。
但是,我不知道该如何从mixins访问this
(VueInstnce)?
Vue不支持,因为mixin首先运行在组件代码之前,然后mixin被Vue绑定(合并)到组件实例,因此很容易从组件/实例范围访问mixin,反之则不然。
为了满足您的需要,我认为应在给定引用组件实例作为参数的情况下运行(例如created
之类的mixin方法,但事实并非如此。
但是,如果您重新组织代码以运行instance
中需要的代码。created
可以访问mixin的方法和数据并自行传递参数:
var mixin = {
data: {mixin: 'mixin'},
created: function () {
console.log('mixin hook called')
},
methods: { test: function(arg){console.log(arg); } }
};
vm=new Vue({
data: {component: 'component'},
mixins: [mixin],
created: function () {
console.log('called hook of ' + this.component + ' and accessing ' + this.mixin)
},
});
vm.test(vm.mixin);
vm.test(vm.component); // no problem to run mixin's method with component's data
> mixin hook called
> called hook of component and accessing mixin
> mixin
> component