0

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: []
  }
})

2 Answers 2

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/

Sign up to request clarification or add additional context in comments.

Comments

3

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

1 Comment

Thanks dude, found this after a struggle with a messy code!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.