如何从 mixins 访问 Vue 实例?

db0*_*99u 5 vue.js vuex nuxt.js

我想实现这种分配this.$store.value给本地数据的逻辑。例如,这就是我在pages/index.vue 中所做的事情。

method: {
  this.value = this.$store.value
}
Run Code Online (Sandbox Code Playgroud)

我想把它写进 mixin 中,因为我实际上有另一个围绕它的逻辑,并且我使用了一些页面。

但是,我不知道应该如何this从 mixins 访问 (VueInstnce) ?

Sła*_*art 1

Vue 不支持它,因为 mixin 首先在组件代码之前运行,然后 Vue 将 mixin 绑定(合并)到组件实例,因此可以轻松地从组件/实例范围访问 mixin,但反之则不然。

为了实现您的需求,我认为 mixin 方法(例如created)应该以对组件实例的给定引用作为参数来运行(例如),但事实并非如此。

但是,如果您重新组织代码以从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
Run Code Online (Sandbox Code Playgroud)
> mixin hook called
> called hook of component and accessing mixin
> mixin
> component
Run Code Online (Sandbox Code Playgroud)