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

完成~

相关推荐
谭光志10 小时前
Vibe Coding 时代,程序员该何去何从
前端·后端·ai编程
仿生狮子12 小时前
别再说“全栈”了,AI 时代团队只认这 5 种人
前端·人工智能·后端
kyriewen12 小时前
AI 写的 React 组件,合并前必查的 6 个坏味道——每个都有代码对比
前端·javascript·react.js
Highcharts.js12 小时前
软件开发公司为什么选择 Highcharts?
前端·前端框架·echarts·数据可视化·技术选型·highcharts·图表工具
多加点辣也没关系12 小时前
JavaScript|第13章:原始类型的方法
开发语言·javascript·ecmascript
এ慕ོ冬℘゜12 小时前
深入理解 JavaScript 事件体系:Window、鼠标与键盘事件详解
开发语言·javascript·okhttp
阿祖zu13 小时前
企业 AI 转型之痛,个人提效十倍不止,组织效率仍止步不前?
前端·aigc·agent
摇滚侠14 小时前
SpringBoot3+Vue3 全套视频教程 45-51
前端·javascript·vue.js
酸梅果茶14 小时前
【6】lightning_lm项目-LIO 前端 -点云预处理模块
前端·slam
触底反弹14 小时前
🔥 RAG 到底是怎么工作的?掰开揉碎了给你讲明白!
javascript·人工智能·后端