【发布时间】:2019-09-15 17:30:10
【问题描述】:
我在使用 mixins 时遇到了一个问题。我不确定是 mixins 本身的一些限制,还是访问 mixins 数据的错误;用谷歌搜索了我的问题,但似乎没有人报告这个问题。所以让我在这里详细说明:
我一直在构建一个 Vue 应用程序,最近我修改了我的 Vue 组件。核心组件,比如 mainCompo,包含各种子组件。
mixin,假设 viewer.js 看起来像这样:
export const viewer = {
data() {
return {
foo:"bar",
hello:"world"
}
},
methods: {
testFunc() {
console.log("test func");
}
},
computed: {
testComputed(){
return "123";
}
}
主要组件 mainCompo 看起来像这样:它包含许多组件。 所以 compoChildA、compoChildB 和 compoChildC ...等都是 mainCompo 的子级。
import {viewer} from 'mixins/viewer';
export default {
components: {
compoChildA,
compoChildB,
compoChildC
},
mixins: [viewer],
data() {
//...
}
mounted() {
console.log(this.testComputed);
console.log(this.foo);
console.log(this.hello);
console.log(this.testFunc());
},
//....
}
<div>
<compo-child-a></compo-child-a>
<compo-child-b></compo-child-b>
<compo-child-c></compo-child-c>
...
</div>
我们以一个子组件 compoChildA 为例:
import {viewer} from 'mixins/viewer';
export default {
mixins: [viewer],
data() {
//...
}
mounted() {
console.log(this.testComputed);
console.log(this.foo);
console.log(this.hello);
console.log(this.testFunc());
},
//....
}
<div>
...
</div>
现在,mainCompo 的mounted() 钩子中的所有控制台日志都按预期输出了数据:
this.testComputed --> 123
this.foo --> bar
this.hello --> world
this.testFunc() --> test func
但是,在 compoChildA 的情况下,结果如下:
this.testComputed --> 123
this.foo --> undefined
this.hello --> undefined
this.testFunc() --> test func
最令人困惑的部分是computed()数据可以访问,但是没有data()!?
所以问题是: 是否意味着只有 mixins 中的 data() 不能通过子组件访问。
也就是说,我正在考虑是否正确使用 mxins。 我已经阅读了官方的 Vue 文档。该示例显示数据也可以在 mixins 中设置。 mixins的使用是组件之间共享共同的东西,所以应该有办法获取mixins的数据。
但是,store 可能是获取数据的更合适的方式,所以我想知道我是否应该改为使用 store 来代替?
【问题讨论】:
-
Mixins 被“混合”到它们被导入的组件中,数据应该被这样对待。与任何其他组件一样,您希望与子组件共享的任何数据或方法都应使用 props 传递。
-
是的,在某些情况下我确实使用道具。这很好,但有时我必须更改从父传递的数据。 Vuez store 可以解决这个问题。但是,在某些情况下,只有一个子组件需要更改数据。我尝试使用事件总线,它是一个简单的实现,但它不容易维护。这就是我转向使用 mixin 的原因。现在由于子组件似乎无法访问 mixin 数据,我认为 vuez store 将是最好和最干净的方式。..
标签: javascript vue.js