vue.js - 如何从 mixins 访问 Vue 实例?
问题描述
我想实现这种分配this.$store.value
给本地数据的逻辑。例如,这就是我在 pages/index.vue 中的做法。
method: {
this.value = this.$store.value
}
我想把它写成 mixins,因为我实际上有其他逻辑围绕它,并且我使用了一些页面。
但是,我不知道应该如何this
从 mixins 访问(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
推荐阅读
- reactjs - 如何从天气 API 数组(对于 React Redux)中获取单独的每日数组,该数组每 3 小时提供 5 天报告
- stata - 分组结果的汉明距离
- flutter - 从建议列表中选择项目时显示 json 数据
- time-complexity - 为什么n点FFT等于截断数据,是否使FFT的复杂度为O(1)?
- python - 如何使用标签创建 Python 树视图并稍后使用 QTreeWidget => PyQt 获取项目坐标
- python - 如何使用用户输入来调用用户定义的函数?
- video - 我需要跟踪有关谁下载了我的视频内容的信息
- node.js - 如何从 nodejs 中的谷歌存储桶中读取二进制文件?
- java - Java Reactor:有没有办法改造 Flux
> 进入通量 没有急切的获取? - python - 如何提取员工在熊猫轮班期间所做的第一个和最后一个条目