前端实现标签默认全选与点击标签选中切换
整体展示效果图
html代码
<div class="filterBox">
<div class="filterTitle">
请选择
</div>
<div class="filterContent">
<span v-for="(item,index) in company" :key="index" :class="selectCompanyId.indexOf(item.id)!==-1? 'defaultSty':' cancelSty'" @click="selectCompany(item)">{{ item.name }}</span>
</div>
</div>
JavaScript代码
<script>
export default {
data() {
return {
selectCompanyId: [1, 2, 3, 4],
company: [
{
id: 1,
name: '小米'
}, {
id: 2,
name: '华为'
}, {
id: 3,
name: '腾讯'
}, {
id: 4,
name: '阿里巴巴'
}
]
}
},
methods: {
// 选择
selectCompany(data) {
//最开始默认选中所有数据 第一次点击时取消所有数据选中状态 只保留点击标签的选中状态
if (this.selectCompanyId.length === this.company.length) {
this.selectCompanyId = []
}
if (this.selectCompanyId.indexOf(data.id) === -1) {
this.selectCompanyId.push(data.id)
} else {
//再次点击选中的标签时 取消选中状态
this.selectCompanyId.splice(this.selectCompanyId.indexOf(data.id), 1)
}
this.selectContent.push(data)
},
}
}
</script>
样式代码
使用的less编写
// 样式
.filterBox{
width: 100%;
padding-left: 0.1rem;
.filterTitle{
width: 100%;
margin: 0.2rem 0;
text-align: left;
color: #333333;
font-size: 0.4rem;
}
.filterContent{
width: 100%;
display: flex;
flex-direction: row;
justify-content: space-around;
flex-wrap: wrap;
align-items: center;
span{
display: inline-block;
width: 44%;
padding: 0.3rem;
font-size: 0.36rem;
text-align: center;
}
.defaultSty{
color: #596DFF;
background: rgba(152,164,249, 0.2);
border:1px solid #596DFF;
}
.cancelSty{
color: #333;
background: #F2F2F2;
border:1px solid #F2F2F2;
}
:nth-child(3){
margin: 0.3rem 0;
}
:nth-child(4){
margin: 0.3rem 0;
}
}
}