1. 实现思路
- 为每个按钮设置一个index;
- 为按钮设置点击事件
- 获取到按钮点击事件以后,判断index,进而动态修改按钮的class
2. 代码实现
2.1 代码
<template>
<div class="btnGroup">
<button
v-for="(item, index) in listData"
:key="index"
@click="changeColor(index)"
:class="activeIndex === index ? 'active' : ''"
>
{{ item }}
</button>
</div>
</template>
<script>
export default {
data() {
return {
listData: ["Button1", "Button2", "Button3", "Button4", "Button5"],
activeIndex: null,
};
},
methods: {
changeColor(index) {
this.activeIndex = index;
}
}
};
</script>
<style lang="less" scoped>
.btnGroup {
width: 500px;
height: 100px;
button {
width: 15%;
height: 35%;
margin: 20px 0 20px 20px;
background-color: pink;
border: 1px solid skyblue;
}
.active {
background-color: antiquewhite;
}
}
</style>
2.2 实现效果