关于vue选中按钮判断样式包括点击添加再点击去掉
<!-- 区域 -->
<div class="size-box">
<div class="size-title fs-24 flex-center">
<span class="color-333 fs-24">{{currentArea.size}}</span>
<span class="color-667 fs-24 ml-30">不限区域</span>
<div class="flex-center" @click="showArea()">
<span class="color-b3 fs-24" style="margin-left:2.25rem">可选区县</span>
<van-icon name="arrow" color="#B3B3B3"/>
</div>
</div>
<div class="size fs-24 color-000">
<span v-for="(item,index) in currentArea.content"
:key="index"
:class="{active:activeArea(item.size)}"
@click="getSelectArea(item.size)"
>{{item.size}}</span>
</div>
</div>
// 区域选择条件
getSelectArea(value) {
var exit = false;
if (this.getArea.includes(value)) {
/*根据值删除*/
Array.prototype.contains = function (obj) {
console.log(this)
var i = this.length;
while (i--) {
if (this[i] === obj) {
return i;
}
}
return false;
}
this.getArea.splice(this.getArea.contains(value), 1)
exit = true;
}
if (exit) {
console.log("存在已被删除")
} else if (!exit) {
this.getArea.push(value)
console.log("不存在已被添加")
}
return exit;
},
activeArea(value) {
if (this.getArea.includes(value)) {
return true;
} else {
return false;
}
},
还有一个方法,就是添加一个flag来判断
getSelectBusiness(value){
console.log(value)
this.businData.forEach(item=>{
if(item.text == value){
if(item.flag == 0){
item.checked = true
item.flag = 1
}else{
item.checked = false
item.flag = 0
}
}
})
this.$store.commit("changeBusinessData", this.businData)
},
前提是循环先把flag添加到数据里面,注意设置属性的话要考虑响应式属性
如下面操作
let data = {
size: '非商业信息',
checked:false,
children:[
{id:12340,size:'不限',checked:false},
{id:12341,size:'失物启示',checked:false},
{id:12342,size:'公告通知',checked:false},
{id:12343,size:'公益宣传',checked:false},
{id:12344,size:'祝福庆贺',checked:false},
{id:12345,size:'其他非商业信息',checked:false},
]
},
{
size: '食品',
checked:false,
children:[
{size:'不限',checked:false},
{size:'食品1',checked:false},
{size:'食品2',checked:false},
{size:'食品3',checked:false},
]
},
// 替换掉后端字段 size 因为vant-select 固定里面的text
data.map((item) => {
item.text = item.size;
item.flag = 0
// delete item.size;
// item.children = item.son;
item.children.map((item2) => {
item2.text = item2.size;
item2.flag = 1
// delete item2.size;
});
});
// console.log(data);
this.selectedInfo = data;
this.$store.commit("changeBusinessData",this.selectedInfo)
注意请求数据后添加flag和checked用于判断
使用排他思想,先清除所有样式,再给点击这个添加样式