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);
					}
				}
			},

完成~

相关推荐
天***889620 分钟前
Chrome扩展安装插件教程,Edge安装插件扩展教程,浏览器安装扩展程序方法
前端·chrome·edge
心.c1 小时前
深拷贝浅拷贝
开发语言·前端·javascript·ecmascript
IT_陈寒1 小时前
Vue 3.4性能优化实战:5个鲜为人知的Composition API技巧让打包体积减少40%
前端·人工智能·后端
前端九哥1 小时前
💻【急招!27届前端实习生】广州4399实习太幸福了!江景+三餐+健身房全都有😭
前端·面试·招聘
咖啡の猫2 小时前
Vue全局事件总线
前端·javascript·vue.js
Lovereo2 小时前
我的目标检测性能优化之路:预算不够、GPU 没有、但性能我得要
前端
T___T2 小时前
JavaScript 变量声明详解:var、let、const 的核心差异
javascript·面试
蒙娜丽宁2 小时前
Rust 与 WebAssembly:构建高效前端应用的全流程复盘
前端·rust·wasm
这儿有一堆花2 小时前
使用 Actix-web 开发高性能 Web 服务
前端·数据库
豆苗学前端2 小时前
10分钟带你入门websocket,并实现一个在线多人聊天室
前端·javascript·后端