0

A few days ago I started using vue.js and trying to get the hang of it.

I've been fiddling quite a bit to get this easy example to work: reading the value of selected checkboxes in components with vue.js .

Please see my example on http://jsbin.com/gukoqo/edit?html,js,output

How can I let selected in the parent instance contain the selected values of the checkbox? E.g., filter_a and filter_c are selected, then selected should contain an array: ['filter_a', 'filter_c']

I expected vue.js to make this very easy, but don't know yet how to. Anyone? :)

I'm using the latest vue.js (2.3.3 at the moment)

1 Answer 1

1

One possible way.

Vue.component('facet-filter', {
  props: ['filter', 'checked'],

  template: `<div>
              <label class="form-check-label">
                <input @change="$emit('change', filter.text, $event)" 
                       class="form-check-input" 
                       type="checkbox" 
                       :value="filter.text" 
                       :checked="checked" 
                       name="filters"> {{filter.text}}
              {{$props | json 2}}</label>
            </div>`,
});

new Vue({
  el: '#app',
  data: {
    filterFacets: [
      { id: 0, text: 'filter_a' },
      { id: 1, text: 'filter_b' },
      { id: 2, text: 'filter_c' },
      { id: 3, text: 'filter_d' },
    ],
    selected: [], // How can I let this contain ['filter_a', 'filter_b'] etc. when selected?
  },
  methods:{
    onChange(filter, $event){
      if ($event.target.checked)
        this.selected.push(filter)
      else {
        const index = this.selected.findIndex(f => f === filter)
        if (index >= 0)
          this.selected.splice(index, 1)
      }
    }
  }
});

And change your template to

<div id="app">
  <facet-filter
    v-for="item in filterFacets"
    v-bind:filter="item"
    v-bind:checked="selected.includes(item.text)"
    :key="item.id"
    @change="onChange"
    >
  </facet-filter>
  <p><pre>data: {{$data | json 2}}</pre></p>
</div>

Updated bin.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot, appreciated! To be honest, I was a little afraid of this already :) It seems to add a lot of complexity for such a simple thing. I'll dive into your example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.