Vue: checkboxes with array model

Created on 11 Jul 2015  ·  3Comments  ·  Source: vuejs/vue

How do I get something like this to work?:

<script>
new Vue({
  data: {
    languages: ['english', 'japanese', 'chinese']
    myLanguages: ['english', 'chinese']
  }
});
</script>
<span v-repeat='language : languages'>
  <input
    type='checkbox'
    value='{{ language }}'
    v-model='myLanguages'>
</span>

Most helpful comment

What exactly are you wanting to happen?
If it's a list of checkboxes and their checked state, you could hold the languages as an object rather than a string.

<script>
new Vue({
  data: {
    languages: [
        {name: 'english', checked:true},
        {name: 'japanese', checked:false},
        {name: 'chinese', checked:true}
    ]
  }
});
</script>
<span v-repeat='language : languages'>
  <input
    type='checkbox'
    value='{{ language.name }}'
    v-model='language.checked'>
</span>

You can then use a filter/map to retrieve the names of the selected languages.

Here's a jsfiddle demonstrating it. http://jsfiddle.net/rmp135/v9vx9qyd/

All 3 comments

What exactly are you wanting to happen?
If it's a list of checkboxes and their checked state, you could hold the languages as an object rather than a string.

<script>
new Vue({
  data: {
    languages: [
        {name: 'english', checked:true},
        {name: 'japanese', checked:false},
        {name: 'chinese', checked:true}
    ]
  }
});
</script>
<span v-repeat='language : languages'>
  <input
    type='checkbox'
    value='{{ language.name }}'
    v-model='language.checked'>
</span>

You can then use a filter/map to retrieve the names of the selected languages.

Here's a jsfiddle demonstrating it. http://jsfiddle.net/rmp135/v9vx9qyd/

I guess the use case is to use the check boxes in a similar manner that
your use a select with the ability to select multiple selections. Sort of
a "check all that apply" scenario, where the checkables come from an array
of possibilities.
On Jul 12, 2015 9:43 AM, "rmp135" [email protected] wrote:

What exactly are you wanting to happen?
If it's a list of checkboxes and their checked state, you could hold the
languages as an object rather than a string.


type='checkbox'
value='{{ language.name }}'
v-model='language.checked'>

You can then use a filter/map to retrieve the names of the selected
languages.

Here's a jsfiddle demonstrating it. http://jsfiddle.net/rmp135/v9vx9qyd/


Reply to this email directly or view it on GitHub
https://github.com/yyx990803/vue/issues/1037#issuecomment-120721497.

Old example here: http://jsfiddle.net/yyx990803/1onz2ho7/1/

Please open questions like this at vuejs/Discussion instead of the core repo.

Was this page helpful?
0 / 5 - 0 ratings