VueJS最初将第一个单选按钮标记为“已选中”

时间:2018-07-16 15:19:14

标签: vue.js radio-button

最初如何将第一个单选按钮标记为“已选中”?

items =
  [
    {txt: 'foo', val: 1},
    {txt: 'bar', val: 2}
  ]


<div  v-for="item in items">
   <input name="myfield" type="radio" v-bind:value="item.val" v-bind:checked="item.val==comparisonvalue">
   <label>{{ item.txt }}</label>
</div>

1 个答案:

答案 0 :(得分:0)

您可能想使用v-modelinput绑定到数据,在这种情况下,请在数据中设置一个项目(例如myInput),然后使用第一个值对其进行初始化在您的项目数组中:

new Vue({
  el: '#app',
  data: {
    myInput: 1,
    items:
      [
        {txt: 'foo', val: 1},
        {txt: 'bar', val: 2}
      ]
  }
})
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script>

<div id='app'>
  <div v-for="item in items">
    <input 
      name="myfield" 
      type="radio"  
      v-bind:value="item.val"
      v-model="myInput">
    <label>{{ item.txt }}</label>
  </div>
</div>


在大多数情况下,您可能会从API调用中获得items,然后可以在created中对其进行初始化:

new Vue({
  el: '#app',
  data: {
    myInput: null,
    items: null
  },
  created () {
    this.items = [
        {txt: 'foo', val: 1},
        {txt: 'bar', val: 2}
      ]   // or from an API call
    this.myInput = this.items[0].val
  }
})
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script>

<div id='app'>
  <div v-for="item in items">
    <input 
      name="myfield" 
      type="radio"  
      v-bind:value="item.val"
      v-model="myInput">
    <label>{{ item.txt }}</label>
  </div>
</div>


或者在index中获得v-for,然后在index === 0处检查input

new Vue({
  el: '#app',
  data: {
    items:
      [
        {txt: 'foo', val: 1},
        {txt: 'bar', val: 2}
      ]
  }
})
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script>

<div id='app'>
  <div v-for="(item, index) in items">
    <input 
      name="myfield" 
      type="radio"  
      v-bind:value="item.val" 
      v-bind:checked="index === 0">
    <label>{{ item.txt }}</label>
  </div>
</div>