Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue.js checkbox component multiple instances

I have a list of filters using checkboxes. I'm trying to make each checkbox it's own components. So I loop through my list of filters adding a checkbox component for each filter. The Vue.js documentation says that if I have multiple checkboxes that use the same model that array will get updated with the value of the checkboxes. I see that working if the group of checkboxes is part of the parent component. But if I make the checkbox a component and add each checkbox component in a loop then the model doesn't update as expected.

How can I have a checkbox component that updates an array on the parent? I know I can do this with emitting an event for a method on the component that updates the array but the Vue documentation makes it seems like the framework does this for you.

Here is a code sample I've been playing around with https://www.webpackbin.com/bins/-KwGZ5eSofU5IojAbqU3

like image 263
Michael Turnwall Avatar asked Jan 30 '23 10:01

Michael Turnwall


1 Answers

Here is a working version.

<template>
  <div class="filter-wrapper">
    <input type="checkbox" v-model="internalValue" :value="value">
    <label>{{label}}</label>
  </div>
</template>

<script>
  export default {
    props: ['checked','value', 'label'],
    model: {
      prop: "checked"
    },
    computed:{
      internalValue: {
        get(){return this.checked},
        set(v){this.$emit("input", v) }
      }
    }
  }
</script>

Updated bin.

like image 80
Bert Avatar answered Feb 01 '23 00:02

Bert