深入解析Vue的input:checkbox的v-model雙向綁定實(shí)現(xiàn)源碼

今天工作時(shí)候遇到了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>權(quán)限設(shè)置</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) {
      // 選中了往數(shù)組checkboxList里push標(biāo)簽value綁定值 
      // 如果是數(shù)字會(huì)被轉(zhuǎn)換成字符串 需要parseInt()!!
      this.checkboxList.push(parseInt(e.target.value))
    } else {
      // 傳入的i 就是存到checkboxList數(shù)組里的值
      // this.checkboxList.indexOf(i)獲取位置
      // this.checkboxList.splice()刪除它!
      this.checkboxList.splice(this.checkboxList.indexOf(i), 1)
    }  
  },
},
屏幕錄制2020-02-2819.46.48.gif
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容