前言
相信大家都使用过 app 的评价功能吧,那下面这张图片你应该很熟悉,今天我们要实现的就是这个需求。首先循环渲染后台返回的数据,这些标签可以点击,点击后会是另一套样式,再次点击恢复默认样式,同时,这些标签可以多选,最后将选中标签的 id 作为集合传给后台。
实现效果
实现思路
- 在模板部分,使用
v-for
指令遍历lists
数组,生成多个<div>
元素,每个元素都包含一个<span>
标签用于显示标签的值。通过:key
绑定每个元素的唯一标识; - 在
<span>
标签上使用 :class 绑定,根据gather
数组中是否包含当前标签的id
来动态添加或移除tagAlter
类,实现选中效果; - 在
<span>
标签中显示标签的值,通过{{ item.value }}
绑定;在<div>
元素上绑定@click
事件,当点击标签时调用onPitch
方法,并传入当前标签的id
作为参数; - 在
data
中定义了lists
数组,包含了多个标签对象,每个对象包含了标签的值和唯一的id
; - 定义了
gather
数组,用于存储选中的标签的id
;定义了stringList
变量,用于存储选中标签的id
拼接成的字符串; - 在
methods
中定义了onPitch
方法,用于处理标签的选中和取消选中操作。如果gather
数组中已经包含当前标签的id
,则从数组中移除该id
;否则,将该id
添加到数组中; - 在
onPitch
方法中,使用join
方法将gather
数组中的元素以逗号分隔拼接成字符串,并赋值给stringList
变量; - 最后,在控制台输出
stringList
和一个提示信息,用于验证选中的标签。
实战环节
下面是我写的一个小案例,大家可以直接复制粘贴到自己的项目中,借助代码和注释,可以更快帮助大家理解。
<template>
<div class="tagBox">
<div v-for="(item, index) in lists" :key="index" @click="onPitch(item.id)">
<span class="tagContant" :class="{ tagAlter: gather.includes(item.id) }">{{ item.value }}</span>
</div>
</div>
</template>
<script>
export default {
data() {
return {
lists: [
{ value: "运行稳定", id: "85" },
{ value: "快速响应", id: "23" },
{ value: "售后及时", id: "12" },
{ value: "解答专业", id: "78" },
],
gather: [],
stringList: null,
};
},
methods: {
onPitch(id) {
if (this.gather.includes(id)) {
this.gather.splice(this.gather.indexOf(id), 1);
} else {
this.gather.push(id);
}
this.stringList = this.gather.join(",");
console.log(this.stringList, "选中集合");
},
},
};
</script>
<style scoped>
.tagBox {
display: flex;
padding: 0px 8px;
}
.tagContant {
display: flex;
align-content: center;
justify-content: center;
font-size: 14px;
width: 80px;
padding: 3px 0px;
color: rgb(161, 161, 161);
border: 1px solid rgb(161, 161, 161);
border-radius: 4px;
margin: 10px 4px;
}
.tagAlter {
background-color: rgb(252, 242, 233);
color: rgb(216, 122, 62);
border: 1px solid rgb(216, 122, 62);
}
</style>