vue中实现点击给当前元素添加class(单选);给点击元素添加class(多选)
比如有一个价格div(这里因为是uniapp所以所有的div都写为view),是v-for循环tags对象中的price数组生成的,price里面有name即价格。点击该元素让当前点击项的class为actived,其他的为空(该元素有默认的class:price-tag)。代码如下:<view class="filter-list flex"><view v-for="(ite
·
一、单选情况
比如有一个价格div(这里因为是uniapp所以所有的div都写为view),是v-for循环tags对象中的price数组生成的,price里面有name即价格。点击该元素让当前点击项的class为actived,其他的为空(该元素有默认的class:price-tag)。
代码如下:
<view class="filter-list flex">
<view v-for="(item,index) in tags.price" :key="index">
<view ref="price" class="price-tag" :class="currentIndex === index ?'actived':''"
@click="checkPrice(index)">{{'¥'+item.name}}
</view>
</view>
</view>
// 在data里面定义currentIndex默认为0
currentIndex:0, //当前索引
tags:{
price: [{
name: '0~150'
},
{
name: '150~300'
},
{
name: '300~450'
}]
}
// 在methods中定义checkPrice方法,让currentIndex=index
checkPrice(index) {
this.currentIndex = index;
},
在methods中要想获取当前点击元素的具体价格,通过this.tags.price[this.currentIndex].name即item.name
二、多选情况
比如有一个服务的div(这里因为是uniapp所以所有的div都写为view),是v-for循环tags对象中的serve数组生成的,serve里面有name即服务。点击该元素让所有的点击项的class为actived(该元素有默认的class:price-tag)。
代码如下:
<view class="filter-list flex">
<view v-for="(item,index) in tags.serve" :key="index">
<view ref="serve" class="price-tag" :class="{'actived':item.active}" @click="checkServe(index)">{{item.name}}
</view>
</view>
</view>
// 在data里面循环的serve
tags:{
serve: [{
name: '可取消',
active: false
},
{
name: '优选',
active: false
},
{
name: '可预订',
active: false
},]
}
// 在methods中定义checkServe方法,让选中标签的active值取反
checkServe(index) { // 选中服务筛选标签
this.tags.serve[index].active = !this.tags.serve[index].active;
//在methods中要想获取点击元素的具体sever中的name,arr中存的就是所有选中的sever的name值
var arr = []; // 定义空数组,接收遍历的值
this.tags.serve.forEach((item) => {
if (item.active) { // 筛选active为true的加到arr中
arr.push(item.name);
}
})
},
更多推荐
已为社区贡献5条内容
所有评论(0)