Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue - input with multiple checkboxes

I'm rendering some checkboxes based on an array and using a data attribute as the v-model. I'm using Vue2.

However, I end up having all checkboxes checked for some reason, when the value of the v-model equals 1 (I guess it treats it as a bool instead of a number).

I tried v-model.number - without any luck. What am I doing wrong?

My template:

<div v-for="category in categories">
  <input
    type="checkbox"
    v-model.number="item.category"
    :id="'category_' + category.id"
    :value="category.id"
    @change="save"
  />
  <label>{{ item.category }} : {{ category.id }}</label>
</div>

Model Data (item.category):

1

Categories:

[
  {
    "id": 2,
    "name": "news Category 0"
  },
  {
    "id": 7,
    "name": "news Category 1"
  },
  {
    "id": 12,
    "name": "news Category 2"
  },
  {
    "id": 17,
    "name": "news Category 3"
  },
  {
    "id": 22,
    "name": "news Category 4"
  },
  {
    "id": 27,
    "name": "news Category 5"
  },
// other values
]

Screenshot (Ive added item.category and category.id as label text to make it more clear):

Vue checkbox v-model typecasting

like image 688
Qar Avatar asked Jan 24 '17 06:01

Qar


1 Answers

As you are using Multiple checkboxes, you have to give an array in v-model, so your item.category has to be an array: [1].

See the working fiddle: https://jsfiddle.net/mimani/y36f3cbm/

var demo = new Vue({
  el: '#demo',
  data() {
    return {
      categories: [{
        "id": 2,
        "name": "news Category 0"
      },  {
        "id": 92,
        "name": "news Category 8"
      }, {
        "id": 97,
        "name": "news Category 9"
      }],
      item: {
        category: [1]
      }
    };
  }
})
like image 180
Saurabh Avatar answered Sep 22 '22 13:09

Saurabh