Vue——radio、checkbox、select 标签的双向绑定

  • radio

    单选框的双向绑定,每个选项都需要设置 value 值和 v-model ,双向绑定就是绑定的这两个值

    <label for="male">
        <input type="radio" >男
    </label>
    <label for="female">
        <input type="radio" >女
    </label>
    // v-model 必须绑定同一个属性,可以不用设置 name 属性(因为v-model已经确定了单选框的分组)
    
    let vue = new Vue({
        el: '#app',
        data: {
            sex:'男'         //默认值可以通过 v-model 设置初始值实现
        },
    }
    

    :input 一般都需要绑定 label ,因为绑定了点击文字也能选中,优化了用户体验

  • checkbox

    • 单个框(一帮用于用户协议)

      用 v-model 绑定 boolear 值来切换选中状态

      <label for="agree">
          <input type="checkbox" >同意
      </label>
      <h3>{{isAgree}}</h3>
      
      let vue = new Vue({
          el: '#app',
          data: {
              sex:'男',     //设置初始值实现默认选中
              isAgree: false
          }
      })
      
    • 多个框

      每个选项 v-model 绑定相同的数组,数组内存储的是选中的 value

      <label for="apple">
          <input type="checkbox" >苹果
      </label>
      <label for="banana">
          <input type="checkbox" >香蕉
      </label>
      <label for="orange">
          <input type="checkbox" >苹果
      </label>
      <h3>{{fruits}}</h3>
      
      let vue = new Vue({
          el: '#app',
          data: {
              sex:'男',     //设置初始值实现默认选中
              isAgree: false,
              fruits: ['apple']
          },
          methods: {
      
          }
      })
      
  • select

    v-model 写在 select 标签上

    • 单选

      v-mode 绑定字符串

      <select  v-model="city">
          <option value="北京">北京</option>
          <option value="上海">上海</option>
          <option value="广州">广州</option>
      </select>
      <h3>{{city}}</h3>
      let vue = new Vue({
          el: '#app',
          data: {
              sex:'男',     //设置初始值实现默认选中
              isAgree: false,
              fruits: ['apple'],
              city:'北京',
          },
          methods: {
      
          }
      })
      
    • 多选

      v-model 绑定数组,select 设置属性 multiple,按住 ctrl 选中多个

      <select v-model="citys" multiple>
          <option value="北京">北京</option>
      <option value="上海">上海</option>
      <option value="广州">广州</option>
      </select>
      <h3>{{citys}}</h3>
      
      let vue = new Vue({
          el: '#app',
          data: {
              sex:'男',     //设置初始值实现默认选中
              isAgree: false,
              fruits: ['apple'],
              city:'北京',
              citys: []
          },
          methods: {
      
          }
      })