有6个按钮的类名同为red,当我点击一个按钮的时候他的类名从red变成active。其他没有点击的还是red
时间: 2024-03-20 14:40:45 浏览: 11
好的,你可以尝试使用下面的代码实现这个功能:
```
<template>
<div>
<button v-for="(item, index) in buttons" :key="index" :class="{active: activeIndex === index, red: activeIndex !== index}" @click="handleClick(index)">{{ item }}</button>
</div>
</template>
<script>
export default {
data() {
return {
buttons: ['Button 1', 'Button 2', 'Button 3', 'Button 4', 'Button 5', 'Button 6'],
activeIndex: null
}
},
methods: {
handleClick(index) {
this.activeIndex = index
}
}
}
</script>
<style>
.red {
background-color: red;
color: white;
}
.active {
background-color: green;
color: white;
}
</style>
```
在上面的代码中,我们使用了 `v-for` 指令来循环渲染按钮,使用 `:class` 绑定了按钮的类名。当按钮处于激活状态时,会添加 `active` 类名,否则添加 `red` 类名。在 `handleClick` 方法中,我们将 `activeIndex` 设置为当前点击的按钮的索引,从而实现按钮的切换。同时,我们还定义了 `.red` 和 `.active` 两个类名,用来设置按钮的样式。