在Vue JS中,当在数组元素(子元素)的计算属性内进行更改时,我无法监视数组的更改。
我已在我编写的示例JSFiddle中简化了该问题,因此该示例在逻辑上可能没有意义,但确实显示了我的问题。
https://jsfiddle.net/trush44/9dvL0jrw/latest/
我有一个父组件,可以容纳多种颜色。每种颜色均使用子组件进行渲染。子组件具有称为“ IsSelected”的计算属性。当“ IsSelected”计算属性在任何数组元素上更改时,我需要遍历整个数组以查看数组中是否至少还有1个元素被选中,然后相应地设置IsAnyCheckboxChecked。
<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
}
]
}
});
答案 0 :(得分:1)
使用$ refs直接访问子级。在v-for ref内变为and数组。因为您的v-for是基于this.color.length的,所以无论如何都要使用$ ref变量中的相同内容来循环。
https://jsfiddle.net/goofballtech/a6Lu4750/19/
<the-child ref="childThing" inline-template :color="element" :key="index" v-for="(element, index) in colors">
for (var i in this.colors) {
if (this.$refs.childThing[i].IsSelected) {
isAnyCheckboxChecked = true;
break;
}
}