【发布时间】:2020-09-30 09:06:21
【问题描述】:
在 Vue JS 中,当在数组元素(子)的计算属性中进行更改时,我无法观察数组的更改。
我已经在我编写的示例 JSFiddle 中将问题归结为问题,因此该示例在逻辑上可能没有意义,但它确实显示了我的问题。
https://jsfiddle.net/trush44/9dvL0jrw/latest/
我有一个包含颜色数组的父组件。每种颜色都使用子组件进行渲染。子组件有一个名为“IsSelected”的计算属性。当任何数组元素上的“IsSelected”计算属性发生变化时,我需要遍历整个数组以查看是否仍然选择了数组中的至少 1 个元素,然后相应地设置 IsAnyCheckboxChecked。
- 你能帮我理解我是否在做我的计算和观察 正确吗?
- 在-parent组件的watch中,为什么this.colors[i].IsSelected 即使 IsSelected 在 DOM 中渲染得很好,也返回 undefined?
<div id="app">
Is any Color Selected?...... {{IsAnyCheckboxChecked}}
<the-parent inline-template :colors="ColorList">
<div>
<the-child inline-template :color="element" :key="index" v-for="(element, index) in colors">
<div>
{{color.Text}}
<input type="checkbox" v-model="color.Answer" />
IsChecked?......{{IsSelected}}
</div>
</the-child>
</div>
</the-parent>
</div>
Vue.component('the-child', {
props: ['color'],
computed: {
IsSelected: function () {
return this.color.Answer;
}
}
});
Vue.component('the-parent', {
props: ['colors'],
watch: {
colors: {
handler: function (colors) {
var isAnyCheckboxChecked = false;
for (var i in this.colors) {
// IsSelected is undefined even though it's a 'computed' Property in the-grandchild component
if (this.colors[i].IsSelected) {
isAnyCheckboxChecked = true;
break;
}
}
this.$parent.IsAnyCheckboxChecked = isAnyCheckboxChecked;
},
deep: true
}
}
});
// the root view model
var app = new Vue({
el: '#app',
data: {
'IsAnyCheckboxChecked': false,
'ColorList': [
{
'Text': 'Red',
'Answer': true
},
{
'Text': 'Blue',
'Answer': false
},
{
'Text': 'Green',
'Answer': false
}
]
}
});
【问题讨论】:
标签: vue.js vue-component