gpt4 book ai didi

vue.js - 如何从mixin访问Vue实例?

转载 作者:行者123 更新时间:2023-12-04 11:41:47 28 4
gpt4 key购买 nike

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

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

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

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

最佳答案

Vue 不支持它,因为 mixin 在组件代码之前先运行,
然后 mixin 被 Vue 绑定(bind)(合并)到组件实例,因此很容易从组件/实例范围访问 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

> mixin hook called
> called hook of component and accessing mixin
> mixin
> component

关于vue.js - 如何从mixin访问Vue实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53078211/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com