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

完成~

相关推荐
共享家95275 小时前
搭建 AI 聊天机器人:”我的人生我做主“
前端·javascript·css·python·pycharm·html·状态模式
Halo_tjn6 小时前
基于封装的专项 知识点
java·前端·python·算法
摘星编程6 小时前
OpenHarmony环境下React Native:自定义useTruncate文本截断
javascript·react native·react.js
Duang007_7 小时前
【LeetCodeHot100 超详细Agent启发版本】字母异位词分组 (Group Anagrams)
开发语言·javascript·人工智能·python
2601_949868368 小时前
Flutter for OpenHarmony 电子合同签署App实战 - 主入口实现
开发语言·javascript·flutter
m0_748229998 小时前
Vue2 vs Vue3:核心差异全解析
前端·javascript·vue.js
C澒9 小时前
前端监控系统的最佳实践
前端·安全·运维开发
xiaoxue..9 小时前
React 手写实现的 KeepAlive 组件
前端·javascript·react.js·面试
摘星编程9 小时前
在OpenHarmony上用React Native:自定义useHighlight关键词高亮
javascript·react native·react.js
hhy_smile9 小时前
Class in Python
java·前端·python