在Vue JS中,当在数组元素的(子)计算属性中进行更改时,我无法监视数组的更改。
我已经在我编写的示例JSFiddle中对这个问题做了详细的说明,所以这个例子可能逻辑上没有意义,但它确实显示了我的问题。
https://jsfiddle.net/trush44/9dvL0jrw/latest/
我有一个包含颜色数组的父组件。每种颜色都使用子组件呈现。子组件具有一个名为“IsSelected”的计算属性。当“IsSelected”计算的属性在任何数组元素上发生变化时,我需要遍历整个数组,以查看数组中是否至少选择了一个元素,然后相应地设置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
}
]
}
});发布于 2020-06-10 21:02:53
使用$refs直接访问子节点。在变成和数组内。因为您的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;
}
}https://stackoverflow.com/questions/62312230
复制相似问题