[Vuejs]-Pre checking checkbox using Vuejs and v-model

5πŸ‘

βœ…

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/

πŸ‘€user320487

2πŸ‘

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)
  }
})

Leave a comment