1. 实现思路
为每个按钮设置一个index;为按钮设置点击事件获取到按钮点击事件以后,判断index,进而动态修改按钮的class2. 代码实现
2.1 代码
<template><div class="btnGroup"><buttonv-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"],// 标记被选中的按钮的indexactiveIndex: 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>