单选
需求 :页面上有几个按钮或几个标签或卡片,点击哪个就会有对应的高亮
效果
这里我们使用vue的动态class就可以了
<!--
* @Date: 2022-09-03 16:45:30
* @LastEditors: zhangchao
* @LastEditTime: 2022-09-03 17:29:34
* @FilePath: /平时练习框架/src/layout/Index copy 4.vue
-->
<template>
<div class="box">
<div v-for="(item, index) in list" :key="index">
<span
// content为固定的类 通过三元表达式去判断是否添加激活的类
// 这里判断的逻辑为 通过点击事件将点击的title值赋予name此时三元表达式为true class 为content active
:class="'content ' + (item.title === name ? 'active' : '')"
@click="changeStatus(item.title)"
>{{ item.title }}</span
>
</div>
</div>
</template>
<script>
export default {
data() {
return {
name: "",
list: [
{ title: "张超", id: 1 },
{ title: "二杨哥", id: 2 },
{ title: "舒城吴彦祖", id: 3 },
],
};
},
methods: {
changeStatus(title) {
this.name = title;
},
},
};
</script>
<style scoped lang="scss">
.box {
display: flex;
.content {
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;
}
.active {
background-color: rgb(252, 242, 233);
color: rgb(216, 122, 62);
border: 1px solid rgb(216, 122, 62);
}
}
</style>
多选
效果
<!--
* @Date: 2022-08-24 19:10:26
* @LastEditors: zhangchao
* @LastEditTime: 2022-09-03 16:31:40
* @FilePath: /平时练习框架/src/layout/Index copy.vue
-->
<template>
<div class="tagBox">
<!-- // v-for循环模拟的数组lists -->
<div v-for="(item, index) in lists" :key="index" @click="onPitch(item.id)">
<span
class="tagContant"
:class="{ tagAlter: gather.indexOf(item.id) > -1 }"
>{{ 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: {
//点击事件 通过传参拿到每一条的id
onPitch(id) {
let subscript = this.gather.indexOf(id); //indexOf:返回某个指定的字符串值在字符串中首次出现的位置
if (subscript > -1) {
this.gather.splice(subscript, 1); //splice:用于添加或删除数组中的元素
} else {
this.gather.push(id); //通过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>