uniapp,点击选中并改变颜色,第二次点击取消选中状态

一、效果图

二、代码实现

字符串的indexOf和数组的indexOf用法一致!

arr.indexOf(item) 该方法返回某个元素在数组中的位置。若没检索到,则返回 -1。

c 复制代码
关键代码:(通过:class绑定)
:class="selectList.indexOf(sub.type) !== -1 ? 'right_item right_item_active':'right_item'"

2.1html

c 复制代码
		<view class="right">
			<!-- 通过(selectList.indexOf(sub.type) !== -1)来判断选中的数组里,是否有该元素。
				点击时,如果有,会移除;如果没有,会添加上 
			-->
			<view :class="selectList.indexOf(sub.type) !== -1 ? 'right_item right_item_active':'right_item'"
				v-for="(sub,index) in leftList[tabindex].children" :key="index" @click="rightBtn(sub,index)">
				{{ sub.type }}
			</view>
		</view>

2.2js

c 复制代码
			//点击右侧
			rightBtn(sub, index) {
				console.log(sub, index)
				this.rightindex = index;

				//uniapp 数组添加不重复元素
				if (this.selectList.includes(sub.type)) {
					this.selectList = this.selectList.filter((item) => {
						return item != sub.type;
					});
				} else {
					this.selectList.push(sub.type);
					this.selectList = [...new Set(this.selectList)]; // 数组去重
					if (this.selectList.length > 3) {
						uni.showToast({
							title: "最多选3个",
							icon: "none"
						});
						this.selectList.splice(3, this.selectList.length - 3);
					}
				}
			},

完成~

相关推荐
大怪v1 小时前
AI抢饭?前端佬:我要验牌!
前端·人工智能·程序员
新酱爱学习1 小时前
字节外包一年,我的技术成长之路
前端·程序员·年终总结
小兵张健1 小时前
开源 playwright-pool 会话池来了
前端·javascript·github
IT_陈寒4 小时前
Python开发者必知的5大性能陷阱:90%的人都踩过的坑!
前端·人工智能·后端
codingWhat4 小时前
介绍一个手势识别库——AlloyFinger
前端·javascript·vue.js
Lee川4 小时前
深度拆解:基于面向对象思维的“就地编辑”组件全模块解析
javascript·架构
代码老中医5 小时前
2026年CSS彻底疯了:这6个新特性让我删掉了三分之一JS代码
前端
进击的尘埃5 小时前
Web Worker 与 OffscreenCanvas:把主线程从重活里解放出来
javascript
不会敲代码15 小时前
Zustand:轻量级状态管理,从入门到实践
前端·typescript
踩着两条虫5 小时前
VTJ.PRO 双向代码转换原理揭秘
前端·vue.js·人工智能