Vue父组件访问子组件的compute属性

2024-05-01

在 Vue JS 中,当在数组元素(子元素)的计算属性中进行更改时,我无法监视数组的更改。

我在编写的 JSFiddle 示例中总结了这个问题,因此该示例在逻辑上可能没有意义,但它确实显示了我的问题。

https://jsfiddle.net/trush44/9dvL0jrw/latest/ https://jsfiddle.net/trush44/9dvL0jrw/latest/

我有一个包含颜色数组的父组件。每种颜色都使用子组件呈现。子组件有一个名为“IsSelected”的计算属性。当任何数组元素上的“IsSelected”计算属性发生更改时,我需要循环遍历整个数组以查看数组中是否至少有 1 个元素仍处于选中状态,然后相应地设置 IsAnyCheckboxChecked。

  1. 你能帮我理解我是否正在做计算和观察 正确吗?
  2. 在父组件的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
            }
        ]
    }
});

使用 $refs 直接访问子级。在 v-for ref 内部变成 and 数组。因为你的 v-for 是基于 this.color.length 无论如何使用相同的东西来循环 $ref var 中的值。

https://jsfiddle.net/goofballtech/a6Lu4750/19/ 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;
  }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Vue父组件访问子组件的compute属性 的相关文章

随机推荐