ottz0
ottz0

Reputation: 2605

Pre checking checkbox using Vuejs and v-model

I have a series of checkboxes that are bound to the v-model with a value.

However when you come to the page I need some of the checkboxes pre-checked. I can't use the :checked binding as i'm using the v-model and I need the v-model to pass a value to my checkedNames array.

<div id='example-3'>
  <input type="checkbox" id="jack" value="Jack" v-model="checkedNames" PRE-CHECK-THIS-CHECKBOX>
  <label for="jack">Jack</label>
  <input type="checkbox" id="john" value="John" v-model="checkedNames">
  <label for="john">John</label>
  <input type="checkbox" id="mike" value="Mike" v-model="checkedNames">
  <label for="mike">Mike</label>
  <br>
  <span>Checked names: {{ checkedNames }}</span>
</div>
new Vue({
  el: '#example-3',
  data: {
    checkedNames: []
  }
})

Upvotes: 0

Views: 22664

Answers (2)

user320487
user320487

Reputation:

I took some liberties to modify a few things, but this gets what you're after:

<div id='example-3'>
  <div v-for="(item, index) in names" :key="index">
    <input type="checkbox" :id="item.name" v-model="item.checked">
    <label :for="item.name">{{ item.name }}</label>
  </div>
  <span>Checked names: {{ checkedNames }}</span>
</div>
new Vue({
  el: '#example-3',
  data() {
    return {
      names: [{
        name: 'jack',
        checked: true
      }, {
        name: 'john',
        checked: false
      }, {
        name: 'mike',
        checked: false
      }]
    }
  },
  computed: {
    checkedNames () {
       return this.names.filter(item => item.checked).map(name => name.name)
    }
  }
})

And a working fiddle: https://jsfiddle.net/aj6apozq/8/

Upvotes: 5

Richard Matsen
Richard Matsen

Reputation: 23533

You can use the mounted() hook and a ref attribute on the input.

<div id='example-3'>
  <input type="checkbox" id="jack" value="Jack" v-model="checkedNames" 
    ref="precheck" PRE-CHECK-THIS-CHECKBOX>
   ...
</div>
new Vue({
  el: '#example-3',
  data: {
    checkedNames: []
  },
  mounted() { 
    this.checkedNames.push(this.$refs.precheck.value)
  }
})

Upvotes: 3

Related Questions