v-for 子组件中的复选框值作为 prop(对象数组)

v-for checkbox value in child component as prop (array of objects)

我有两个组件 'Parent' 和 'Child'。每个子组件都有带有 :checked 属性的复选框。在父组件中,我遍历对象数组并将道具传递给子组件。我可以将事件从子项发送回父项并在数组中重新分配新值,我看到了变化但组件没有重新呈现。

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

这是沙盒 link 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", checked: false, id: "02" },
      { title: "Third", checked: false, id: "03" },
      { title: "Fourth", checked: false, id: "04" },
      { title: "Fifth", checked: false, 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,
      required: true
    },
    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

所以在你的代码中,v-bind:value for <input type="checkbox"> inside child.vue 不会切换复选框,它只会改变复选框的值提交表格时。

来自Vue Guide::如下所述:

v-model internally uses different properties and emits different events for different input elements:

text and textarea elements use value property and input event;

checkboxes and radiobuttons use checked property and change event;

select fields use value as a prop and change as an event.

这就是 v-model 的工作方式。

所以在child.vue中,使用:

<input type="checkbox" :checked="checked" @click="$emit('checked', id)">

Updated Code SandBox

您还可以通过使用 getter 和 setter 的计算,使 Child 组件与 v-model 一起工作。我分叉了你的沙箱并在这里做了一个例子:https://codesandbox.io/s/vue-starter-forked-weyzd .