首页 > 解决方案 > 如何从 mixins 访问 Vue 实例?

问题描述

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

method: {
  this.value = this.$store.value
}

我想把它写成 mixins,因为我实际上有其他逻辑围绕它,并且我使用了一些页面。

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

标签: vue.jsvuexnuxt.js

解决方案


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

推荐阅读