vue实现多选、全选功能,不依赖任何第三方组件、插件,复制粘贴开箱即用,简简单单,干净卫生
<template>
<div id="app">
<div class="content">
<div class="selectAll" >
<div :class="['select',SelectId.length==CheckList.length?'selectActv':'']"
@click="allFun()"></div>
<span>全选/反选</span>
</div>
<div class="CheckBox">
<div class="CheckItem" v-for="(item,index) in CheckList" :key="index">
<div :class="['select',SelectId.includes(item.id)?'selectActv':'']"
@click="selectFun(item.id)"></div>
<span>{{item.text}}</span>
</div>
</div>
<div>已选项:</div>
<p v-for="(item,index) in ChooseList" :key="index">
{{item}}
</p>
</div>
</div>
</template>
<script>
export default {
data() {
return {
SelectId: [], // 已选列表
CheckList: [
{id: 1,text: "西瓜"},
{id: 2,text: "葡萄"},
{id: 3,text: "香蕉"},
{id: 4,text: "榴莲"},
{id: 5,text: "柚子"},
{id: 6,text: "枇杷"},
{id: 7,text: "车厘子"},
],
};
},
computed: {
// 被选中项的集合
ChooseList() {
return this.CheckList.filter((item) => {
if (this.SelectId.includes(item.id)) {
return item
}
})
},
},
methods: {
selectFun(id) {
if (!this.SelectId.includes(id)) {
this.SelectId.push(id) // 判断已选列表中是否存在该id,不是则追加进去
} else {
let index = this.SelectId.indexOf(id) // 求出当前id的所在位置
this.SelectId.splice(index, 1) // 否则则删除
}
},
// 全选、反选
allFun() {
if (this.SelectId.length == this.CheckList.length) {
this.SelectId = [] // 判断是否已全部选中,是则清空已选列表
} else {
this.CheckList.forEach((item) => {
if (!this.SelectId.includes(item.id)) {
this.SelectId.push(item.id) // 否则将未选中的全部加入已选列表中
}
})
}
},
}
};
</script>
* {
color: #333;
box-sizing: border-box;
user-select: none;
}
.CheckBox {
width: 100%;
display: flex;
flex-wrap: wrap;
margin: 50px auto;
margin-bottom: 20px;
}
.CheckItem {
display: flex;
margin: 0px 30px 30px 0px;
align-items: center;
}
.select {
width: 20px;
height: 20px;
border-radius: 2px;
border: 1px solid #ccc;
display: flex;
justify-content: center;
cursor: pointer;
margin-right: 10px;
align-items: center;
}
.selectActv::before {
display: block;
content: "";
width: 5px;
height: 12px;
border-bottom: 2px solid #aaa;
border-right: 2px solid #aaa;
transform: rotate(45deg);
}
.selectAll{
display: flex;
}
.content {
width: 500px;
margin: 120px auto;
}
本文转载自: https://blog.csdn.net/m0_59224033/article/details/126709741
版权归原作者 香精煎渔 所有, 如有侵权,请联系我们删除。
版权归原作者 香精煎渔 所有, 如有侵权,请联系我们删除。