深入解析Vue的input:checkbox的v-model双向绑定实现源码

今天工作时候遇到了checkbox的v-model双向绑定问题
话不多说, 直接上代码!
  1. <template>
<template v-for="item of sleectorList">
  <div :key="item.index + 'sleectorList'">
    <input
          type="checkbox"
          :value="item.index"
          :checked="checkboxList.indexOf(item.index) > -1"
          @change="checkHandle($event, item.index)"
    />
    <span>{{ item.value }}</span>
  </div>
</template>

<template v-for="(item, index) of checkboxList">
  <div class="row" :key="item + 'checkboxList'">
    <div class="serve">{{ sleectorList[item].value }}</div>
      <div class="handle">
        <span>权限设置</span>
        <div @click="checkboxList.splice(index, 1)">删除</div>
      </div>
  </div>
</template>
  1. <script>
data() {
    let sleectorList = [
      {
        index: 0,
        value: 'hahaha0',
      },
      {
        index: 1,
        value: 'hahaha1',
      },
      {
        index: 2,
        value: 'hahaha2',
      },
      {
        index: 3,
        value: 'hahaha3',
      },
    ]
    let checkboxList = []
    return { sleectorList, checkboxList }
},
methods: {
  checkHandle(e, i) {
    if (e.target.checked) {
      // 选中了往数组checkboxList里push标签value绑定值 
      // 如果是数字会被转换成字符串 需要parseInt()!!
      this.checkboxList.push(parseInt(e.target.value))
    } else {
      // 传入的i 就是存到checkboxList数组里的值
      // this.checkboxList.indexOf(i)获取位置
      // this.checkboxList.splice()删除它!
      this.checkboxList.splice(this.checkboxList.indexOf(i), 1)
    }  
  },
},
屏幕录制2020-02-2819.46.48.gif
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容