今天工作时候遇到了checkbox的v-model双向绑定问题
话不多说, 直接上代码!
- <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>
- <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