当前位置:首页 > 编程笔记 > 正文
已解决

Vue复选框批量删除示例

来自网友在路上 164864提问 提问时间:2023-09-22 21:23:14阅读次数: 64

最佳答案 问答题库648位专家为你答疑解惑

Vue复选框批量删除

通过使用v-model指令绑定单个复选框
例如<input type="checkbox" id="checkbox" v-model="checked">
而本次我们要做的示例大致是这样的,首先可以增加内容,然后通过勾选来进行单独或者批量删除,但是在此处就可以进行批量操作。
在这里插入图片描述
通过勾选原神和明日进行批量删除后,发现成功了,那么这就是表名咱们的操作没有问题,接下来就要具体代码实现。
在这里插入图片描述

具体代码实现

body中div,挂载点是zjw,也就是张俊伟的缩写,当然这可以自己写什么都行,只要与Vue里面的el对应

<div id="zjw">
<span>添加一条内容</span>
<input placeholder="输入内容" v-model="value"/>
<button @click="add()">添加</button><ul><li v-for="(item,index) in list" :key="index"><input type="checkbox" v-model="item.c"/><span>{{item.d}}</span><button @click="remove(index)">删除</button></li></ul><button @click="removeAll()">批量删除</button>
</div>
<script>const app=new Vue({el:'#zjw',data(){return{list:[{d:'洗碗',c:false},{d:'擦地',c:false}],value:''}},methods:{add(){adds={d:this.value,c:false}this.list.push(adds)this.value=''},remove(i){if(this.list[i].c==true)this.list.splice(i,1)},removeAll(){for (var i = this.list.length - 1; i >= 0; i--)if (this.list[i].c==true) this.list.splice(i, 1);}}})
</script>

分析环节

添加的框

添加操作用@click绑定了一个add()
在input中的v-model是value

<span>添加一条内容</span>
<input placeholder="输入内容" v-model="value"/>
<button @click="add()">添加</button>

下面是script内容
在data中我是用了对象数组来做,里面用了一个c来放复选的状态false没选,true选
而add中也是每次添加的不止文字,还有false或者true,通过this.list.push(adds)加入到数组队尾

data(){return{list:[{d:'洗碗',c:false},{d:'擦地',c:false}],value:''}},methods:{add(){adds={d:this.value,c:false}this.list.push(adds)this.value=''},

对于单个删除和批量操作

这里通过<li v-for="(item,index) in list" :key="index"> <input type="checkbox" v-model="item.c"/> <span>{{item.d}}</span> <button @click="remove(index)">删除</button></li>
来讲data中的数据显示出来,并且可以删除或者批量
button中,使用v-model="item.c"绑定复选框的状态

 <ul><li v-for="(item,index) in list" :key="index"><input type="checkbox" v-model="item.c"/><span>{{item.d}}</span><button @click="remove(index)">删除</button></li></ul><button @click="removeAll()">批量删除</button>

单个删除就是如下操作,一个简单判断this.list[i].c的值就行
对于多选其实也就是多了一个在数组中的循环
for (var i = this.list.length - 1; i >= 0; i--)就可以完成批量删除了

  remove(i){if(this.list[i].c==true)this.list.splice(i,1)},removeAll(){for (var i = this.list.length - 1; i >= 0; i--)if (this.list[i].c==true) this.list.splice(i, 1);}
查看全文

99%的人还看了

猜你感兴趣

版权申明

本文"Vue复选框批量删除示例":http://eshow365.cn/6-11659-0.html 内容来自互联网,请自行判断内容的正确性。如有侵权请联系我们,立即删除!