父组件可以获取 mixins 数据,但不能获取子组件



我在使用 mixins 时遇到了一个问题。我不确定这是 mixins 本身的一些限制,还是访问 mixins 数据的错误;用谷歌搜索了我的问题,但似乎没有人报告过这个问题。因此,让我在这里详细说明:

我一直在构建一个 Vue 应用程序,最近我修改了我的 vue 组件。核心组件,假设 mainCompo,包含各种子组件。

mixins,假设观众.js看起来像这样:

export const viewer =  {
data() {
return {
foo:"bar",
hello:"world"
}
},
methods: {
testFunc() {
console.log("test func");
}
},
computed: {
testComputed(){
return "123";
}
}

主要组件mainCompo看起来像这样:它包含许多组件。 所以 compoChildA、compoChildB 和 compoChildC ...等是主Compo的孩子。

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

最令人困惑的部分是可以访问计算()数据,但没有data()!?

所以问题是: 这是否意味着只有来自 mixins 的数据() 不能通过子组件访问。

也就是说,我在想我是否正确使用了 mxins。 我已经阅读了官方的 Vue 文档。该示例显示数据也可以在混合中设置。 mixins 的用法是在组件之间共享常见的东西,所以应该有某种方法来获取 mixins 数据。

但是,存储可能是获取数据的更合适的方式,所以我想知道我是否应该改为使用存储?

您无法使用 mixins 共享数据。

Mixins 是为 Vue 组件分发可重用功能的灵活方式

你应该使用 Vuex 通过组件实现数据共享。

Mixins 不能通过子组件访问。我以前遇到过这样的问题。 从文档中它指出 "Mixins 是为 Vue 组件分发可重用功能的一种灵活方式。mixin 对象可以包含任何组件选项。当组件使用 mixin 时,mixin 中的所有选项都将"混合"到组件自己的选项中。

它用于功能而不是数据。

https://v2.vuejs.org/v2/guide/mixins.html

最新更新