v-用于子组件中的复选框值作为prop对象数组

问题描述

我有两个部分:“父母”和“孩子”。每个子组件都有一个带有:checked属性的复选框。在父组件中,我遍历对象数组并将道具传递给子对象。我可以将事件从子级发送回父级,并在数组中重新分配新值,我看到了更改,但组件没有重新渲染。

我想做的是在复选框内获得某种无线电组的行为。单击一个复选框后,其他复选框需要设置为false。我可以清楚地看到数组已被修改,但是组件没有重新渲染(

此处的沙盒链接 https://codesandbox.io/s/vue-starter-forked-jxgf9?fontsize=14&hidenavigation=1&theme=dark

父组件:

<template>
  <div>
    <Child
      v-for="l in list"
      :id="l.id"
      :key="l.id"
      :title="l.title"
      :checked="l.checked"
      @checked="handleUpdate"
    />
  </div>
</template>

<script>
import Child from "../components/Child.vue";

export default {
  name: "parent",components: {
    Child
  },data: () => ({
    list: [
      { title: "First",checked: false,id: "01" },{ title: "Second",id: "02" },{ title: "Third",id: "03" },{ title: "Fourth",id: "04" },{ title: "Fifth",id: "05" }
    ]
  }),methods: {
    handleUpdate(e) {
      const newArray = this.list.map(a => ({ ...a }));
      console.log(newArray);

      newArray.forEach(el => {
        if (el.id === e) {
          el.checked = true;
        } else {
          el.checked = false;
        }
      });

      this.list = [];
      this.list = newArray;
    }
  }
};
</script>

子组件:

<template>
  <div>
    <h1>{{ title }}</h1>
    <input type="checkBox" :value="checked" @click="$emit('checked',id)">
  </div>
</template>


<script>
export default {
  name: "child",props: {
    title: {
      type: String,required: true
    },checked: {
      type: Boolean,id: {
      type: String,required: true
    }
  }
};
</script>

任何帮助都是值得赞赏的家伙。我真的坚持了这一点,并感到压力很大(

解决方法

MDN: Checkbox: Additional attributes

Attribute        Description
checked          Boolean; if present,the checkbox is toggled on by default
indeterminate    A Boolean which,if present,indicates that the value of the checkbox is indeterminate rather than true or false
value            The string to use as the value of the checkbox when submitting the form,if the checkbox is currently toggled on

因此在您的代码中, child.vue v-bind:value的{​​{1}}不会切换复选框,它只会在提交表单时更改复选框的值。

来自Vue Guide:的内容:内容如下:

v模型内部使用不同的属性并发出不同的 不同输入元素的事件:

文本和文本区域元素使用值属性和输入事件;

复选框和单选按钮使用选中属性和 change 事件;

选择字段使用值作为道具,并更改为事件。

这就是<input type="checkbox">的工作方式。

因此在 child.vue 中,使用:

v-model

Updated Code SandBox

,

您还可以通过使用带有getter和setter的compute使Child组件与v-model一起使用。我分叉了您的沙箱,并在此处制作了一个示例:https://codesandbox.io/s/vue-starter-forked-weyzd