vue input radio not checked with v-model
Asked Answered
R

1

7

When I use :checked, it works. But if I add v-model, it does not work.

<div v-for="answer in the_data[current].answers" id="answers">
    <p>
        <input
            type="radio"
            name="answer"
            :id="answer"
            :value="answer"
            v-model="the_answer"
            v-bind:checked="answer == 'girl'"
        >  
        @{{ answer }}
    </p>
</div>

I need to use v-model

Romanticize answered 20/1, 2018 at 18:10 Comment(0)
C
9

I believe the reason is the input checked is binded to the_answer and somehow the initial value of the_answer is not one of the picked values, and this binding overwrites the checked attribute, since whatever is checked should be the value the input is binded to, i.e. the_answer. Specifying the initial value of the_answer should give you the same behavior of checked:

new Vue({
  el: '#app',
  data: {
    the_answer: 'girl'               // initialize the_answer to be your checked option
  }
})
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>

<div id='app'>
  <div v-for="answer in ['boy', 'girl']">
    <p>
      <input 
        type="radio" 
        name="answer" 
        :id="answer"
        :value="answer"
        v-model="the_answer">
      @{{ answer }}
    </p>
  </div>
</div>
Celiotomy answered 20/1, 2018 at 18:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.