<!--
* @Author: error: git config user.name && git config user.email & please set dead value or install git
* @Date: 2022-08-04 10:00:00
* @LastEditors: chenzhijie
* @LastEditTime: 2022-08-04 11:06:53
* @FilePath: \demo\test20220804.html
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<!DOCTYPE html>
<html>
<head>
<title>Vue中实现span标签的多选</title>
<script src="https://unpkg.com/vue@2.7.8/dist/vue.js"></script>
</head>
<body>
<div id="app">
<div class="listBox">
<div class="label" @click.stop>
<span v-for="(item, index ) in labelList" :class="{ checked: arr.includes(index) }" :key="index"
@click="checkedBox(item, index)">{{ item }}</span>
</div>
</div>
</div>
<script>
var vm = new Vue({
el: "#app",
data: {
labelList: ["标签1", "标签2", "标签3", "标签4", "标签5"],
arr: [],
list: [],
checked: []
},
methods: {
// 点击多选标签
checkedBox(c, i) {
if (this.arr.includes(i)) {
//includes()方法判断是否包含某一元素,返回true或false表示是否包含元素,对NaN一样有效
//filter()方法用于把Array的某些元素过滤掉,filter()把传入的函数依次作用于每个元素,然后根据返回值是true还是false决定保留还是丢弃该元素:生成新的数组
this.arr = this.arr.filter(function (ele) {
return ele != i;
});
this.list = this.list.filter(function (ele) {
return ele != c;
});
this.checked = this.list
console.log(this.checked);
} else {
this.arr.push(i);
this.list.push(c);
this.checked = this.list
console.log(this.checked);
}
},
},
});
</script>
<style>
.label {
margin-top: 15px;
background-color: #fff;
}
.listBox .label span {
display: inline-block;
margin: 5px;
color: #8c8c8c;
background-color: rgba(210, 222, 242);
height: 24px;
padding: 5px;
border-radius: 2px;
text-align: center;
line-height: 24px;
}
.listBox .label .checked {
color: #1890ff;
background-color: rgba(217, 236, 255);
}
</style>
</body>
</html>
Vue中实现span标签的多选
最新推荐文章于 2024-07-19 11:16:36 发布