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

完成~

相关推荐
汪子熙7 分钟前
走进 Fundamental NGX Platform:从 SAP 设计体系到高生产力组件层
前端·javascript·面试
moxiaoran575313 分钟前
uni-app学习笔记三十四--刷新和回到顶部的实现
笔记·学习·uni-app
拉不动的猪20 分钟前
单点登录全流程小姐
前端·javascript·面试
菜鸟小九27 分钟前
html、css(javaweb第一天)
前端·css·html
y东施效颦1 小时前
uni-app页面发布测试环境出现连接服务器超时,点击屏幕重试解决方案
前端·javascript·vue.js·uni-app·vue
大熊程序猿1 小时前
《开篇:课程目录》
前端·c#
秋田君1 小时前
深入理解JavaScript设计模式之单例模式
javascript·单例模式·设计模式
摸鱼仙人~2 小时前
React中子传父组件通信操作指南
前端·javascript·react.js
程序员阿超的博客2 小时前
React事件处理:如何给按钮绑定onClick点击事件?
前端·javascript·react.js
华子w9089258592 小时前
SpringBoot+uniapp 的 Champion 俱乐部微信小程序设计与实现,论文初版实现
spring boot·微信小程序·uni-app