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

完成~

相关推荐
guslegend27 分钟前
脚手架原理与本地调试:从 bin 软链接到 npm link
前端·npm·node.js·脚手架·前端工程化
小宋102134 分钟前
A2UI从零实战:Agent安全生成交互界面与事件回传
javascript·人工智能·安全·交互
大包子1 小时前
structuredClone vs lodash.cloneDeep:核心差异与选型指南
javascript·vue.js
海码事务所1 小时前
Google Play 新个人开发者账号上架指南:12 人连续 14 天封闭测试怎么做?
前端
田威AI1 小时前
图片内文字翻译的规格:输入输出、保真、自动化、时间与费用
前端·计算机视觉
不可能片场1 小时前
命令行中文变问号 我用环境变量救了场
前端·electron
lerhxx1 小时前
AI 应用中的上下文管理 —— 从"上下文窗口"到"分层压缩"的工程实践
前端·javascript
骑着蜗牛撵大象3272 小时前
多 Agent 分治协作:MapReduce 模式下的并行扇出与结果归并
前端
用户55318297322 小时前
Flutter iOS 热更新深入 Dart VM:读懂函数入口、解释执行与调用桥接
前端
前端snow2 小时前
为什么大厂要用Postgres + mogodb的框架?
前端