mardi 15 septembre 2020

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

I have two components 'Parent' and 'Child'. Each child component has checkbox with :checked prop. In Parent component I iterate through array of object and pass props to child. I can emit event from child back to parent and reassign new value in array, I see changes but the component doesn't re-renders.

What I am trying to do is to get some kinda radio group behaviour but within checkboxes. When one checkbox is clicked others need to be set as false. I can see clearly array has been modified but component doesn't re-renders (

Here's sandbox link https://codesandbox.io/s/vue-starter-forked-jxgf9?fontsize=14&hidenavigation=1&theme=dark

Parent component:

<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>

Child Component:

<template>
  <div>
    <h1></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>

Any help is highly appreciated guys. I really stuck on this and I'm stressed out (




Aucun commentaire:

Enregistrer un commentaire