在Vue 3的项目开发中,我们经常需要通过v-for循环渲染一组按钮,并且需要实现按钮的激活状态切换功能,同时根据业务需求分为单选和多选两种模式。下面分别介绍两种模式的实现方式。

单选模式实现
单选模式的核心逻辑是:同一时间只能有一个按钮处于激活状态,点击新的按钮时,之前激活的按钮会自动取消激活。
实现步骤
- 定义一个响应式变量存储当前激活按钮的唯一标识
- 在v-for循环中为每个按钮绑定点击事件,点击时将该按钮的标识赋值给响应式变量
- 通过动态类名绑定,判断当前按钮的标识是否等于响应式变量的值,来控制激活样式
代码示例
import { ref } from 'vue'
// 按钮列表数据
const btnList = ref([
{ id: 1, label: '按钮1' },
{ id: 2, label: '按钮2' },
{ id: 3, label: '按钮3' }
])
// 当前激活的按钮id,初始为null表示无激活按钮
const activeId = ref(null)
// 点击按钮的处理函数
const handleClick = (id) => {
activeId.value = id
}
<template>
<div class="btn-group">
<button
v-for="item in btnList"
:key="item.id"
:class="['btn', { active: activeId === item.id }]"
@click="handleClick(item.id)"
>
{{ item.label }}
</button>
</div>
</template>
<style scoped>
.btn {
padding: 8px 16px;
margin-right: 10px;
border: 1px solid #ccc;
background-color: #fff;
cursor: pointer;
}
.btn.active {
background-color: #409eff;
color: #fff;
border-color: #409eff;
}
</style>
多选模式实现
多选模式的核心逻辑是:可以同时有多个按钮处于激活状态,点击按钮时会切换自身的激活状态,不影响其他按钮。
实现步骤
- 定义一个响应式数组存储所有激活按钮的唯一标识
- 在v-for循环中为每个按钮绑定点击事件,点击时判断当前按钮标识是否在数组中,存在则移除,不存在则添加
- 通过动态类名绑定,判断当前按钮的标识是否在数组中,来控制激活样式
代码示例
import { ref } from 'vue'
// 按钮列表数据
const btnList = ref([
{ id: 1, label: '按钮1' },
{ id: 2, label: '按钮2' },
{ id: 3, label: '按钮3' }
])
// 存储激活按钮id的数组,初始为空
const activeIds = ref([])
// 点击按钮的处理函数
const handleClick = (id) => {
const index = activeIds.value.indexOf(id)
if (index > -1) {
// 已激活,移除
activeIds.value.splice(index, 1)
} else {
// 未激活,添加
activeIds.value.push(id)
}
}
<template>
<div class="btn-group">
<button
v-for="item in btnList"
:key="item.id"
:class="['btn', { active: activeIds.includes(item.id) }]"
@click="handleClick(item.id)"
>
{{ item.label }}
</button>
</div>
</template>
<style scoped>
.btn {
padding: 8px 16px;
margin-right: 10px;
border: 1px solid #ccc;
background-color: #fff;
cursor: pointer;
}
.btn.active {
background-color: #409eff;
color: #fff;
border-color: #409eff;
}
</style>
两种模式对比
下面是两种模式的核心差异对比:
| 对比项 | 单选模式 | 多选模式 |
|---|---|---|
| 状态存储变量类型 | 单个值(如Number、String) | 数组 |
| 点击处理逻辑 | 直接赋值新的标识 | 判断标识是否存在,进行添加或移除操作 |
| 激活数量限制 | 最多1个 | 无限制 |
注意事项
- 按钮的唯一标识建议使用id等不会重复的值,避免使用索引作为标识,防止列表顺序变化时出现状态错乱
- 如果按钮数据是从接口获取的,需要确保在数据加载完成后再渲染v-for列表,避免初始状态异常
- 动态类名绑定时,建议使用对象语法,可读性更强,也方便扩展更多的状态样式