PriNcee
PriNcee

Reputation: 2607

v-checkbox object model with vuetify

Are v-checkbox vuetify components not working as expected? I'm trying to set an object as value but it seems to not works as I want, did I set something wrong?

<div id="app">
  <v-app id="inspire">
    <v-container fluid>
      <p>{{ selected }}</p>
      <v-checkbox v-model="selected" label="A" value="A"></v-checkbox>
      <v-checkbox v-model="selected" label="my Object with v-checkbox" :value="{ 'id': 1, 'subId': 12 }"></v-checkbox>

<label>
    <input type="checkbox" :value="{ 'id': 1, 'subId': 12 }" v-model="selected">
    my Object with input type checkbox
</label>

    </v-container>
  </v-app>
</div>

JS:

new Vue({
  el: '#app',
  data () {
    return {
      selected: ['A', { "id": 1, "subId": 12 }]
    }
  }
})

Codepen: https://codepen.io/anon/pen/OZYzYw?&editors=101

Upvotes: 1

Views: 23448

Answers (1)

Jacob Goh
Jacob Goh

Reputation: 20845

This is tricky. It's because Javascript object is passed by reference.

Firstly, how to make it work: https://codepen.io/jacobgoh101/pen/KRLQaK?editors=1010

HTML

<div id="app">
  <v-app id="inspire">
    <v-container fluid>
      <p>{{ selected }}</p>
      <v-checkbox v-model="selected" label="A" value="A"></v-checkbox>
      <v-checkbox v-model="selected" label="Object" :value="checkboxObjectValue"></v-checkbox>
    </v-container>
  </v-app>
</div>

Javascript

new Vue({
  el: "#app",
  data() {
    return {
      selected: ["A"]
    };
  },
  created() {
    this.checkboxObjectValue = { id: 11, subId: 12 };
    this.selected.push(this.checkboxObjectValue);
  }
});

Now the explanation...

Javascript object is passed by reference. When you pass an object to something, it's not passing the entire object value, it's passing the reference. I like to think of it as passing the address of an object in memory.

When you do :value="{ 'id': 1, 'subId': 12 }" in v-checkbox, what happen is that everytime this component rerender, a new object is generated and assigned to the value. A new object reference is passed to the value! Therefore, when you pushed it to selected, it's considered a new object, so it just keeps on adding a new object to the selected array.

To avoid this, create an object containing the value first. Then use this same object everywhere to avoid generating a new object. The value object should be generated once only.

Upvotes: 3

Related Questions