V-表示作为道具(对象数组)的子组件中的复选框值

人气:946 发布:2022-10-16 标签: javascript checkbox vue.js nested-loops v-for

问题描述

我有两个组件‘Parent’和‘Child’。每个辅元件都有复选框:选中道具。在父组件中,我迭代对象数组并将道具传递给子组件。我可以将事件从子元素发送回父元素,并在数组中重新分配新值,但组件不会重新呈现。

我试图做的是获得一些无线电群体行为,但不在复选框内。当单击一个复选框时,需要将其他复选框设置为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", 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

因此,在您的代码中,Child.vue内的v-bind:valuefor<input type="checkbox">不会切换复选框,它只在提交表单时更改复选框的值。

来自Vue Guide::声明如下:

V-Model在内部使用不同的属性并发出不同的 不同输入元素的事件:

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

复选框和单选按钮使用选中的属性和更改事件;

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

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

so在Child.vue中使用:

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

Updated Code SandBox

635