Check / Uncheck a Checkbox in a child component with vuejs Check / Uncheck a Checkbox in a child component with vuejs vue.js vue.js

Check / Uncheck a Checkbox in a child component with vuejs


Here is a simplified sample for your reference. You can use the sync modifier to achieve a two-way-binding between the parent and child. That together with a computed property in the child with a setter and getter

So passing all categories to child, and sync the selected categories:

<HelloWorld :cats.sync="selectedCategories" :categories="categories"/>

Child component takes the categories, iterates and shows checkboxes. Here we use the computed property, and when a checkbox is clicked, the setter emits the change to the parent:

<label v-for="c in categories" :key="c.id">  <input v-model="temp" type="checkbox" :value="c">  {{ c.name }}</label>

script:

computed: {  temp: {    get: function() {      return this.cats;    },    set: function(newValue) {      this.$emit("update:cats", newValue);    }  }}

And the parent just simply iterates the selectedCategories and as you wish, when a change happens in parent for selectedCategories, child will be automatically aware of when an item is deleted.

Here's a full sample for your reference: SANDBOX