Vue实现按钮独立激活
Vue 实现按钮独立激活的方法
在 Vue 中实现按钮独立激活(即多个按钮中只有一个保持激活状态)可以通过以下方法实现:
使用 v-model 和计算属性
定义一个响应式数据存储当前激活按钮的索引或标识符,通过计算属性或方法判断按钮是否激活:
<template>
<button
v-for="(btn, index) in buttons"
:key="index"
@click="activeIndex = index"
:class="{ active: activeIndex === index }"
>
{{ btn.text }}
</button>
</template>
<script>
export default {
data() {
return {
activeIndex: null,
buttons: [
{ text: 'Button 1' },
{ text: 'Button 2' },
{ text: 'Button 3' }
]
}
}
}
</script>
<style>
.active {
background-color: #4CAF50;
color: white;
}
</style>
使用组件封装
将按钮逻辑封装为可复用组件,通过 props 和 emits 控制激活状态:
// ToggleButton.vue
<template>
<button
@click="$emit('toggle')"
:class="{ active: isActive }"
>
<slot />
</button>
</template>
<script>
export default {
props: {
isActive: Boolean
}
}
</script>
// Parent.vue
<template>
<ToggleButton
v-for="(btn, index) in buttons"
:key="index"
:isActive="activeIndex === index"
@toggle="activeIndex = index"
>
{{ btn.text }}
</ToggleButton>
</template>
使用 Vuex/Pinia 管理状态
对于复杂应用,可通过状态管理工具集中管理激活状态:
// store.js (Pinia 示例)
import { defineStore } from 'pinia'
export const useButtonStore = defineStore('buttons', {
state: () => ({
activeButtonId: null
}),
actions: {
setActive(id) {
this.activeButtonId = id
}
}
})
// Component.vue
<template>
<button
v-for="btn in buttons"
:key="btn.id"
@click="buttonStore.setActive(btn.id)"
:class="{ active: buttonStore.activeButtonId === btn.id }"
>
{{ btn.text }}
</button>
</template>
<script setup>
import { useButtonStore } from './store'
const buttonStore = useButtonStore()
</script>
动态样式绑定
通过对象语法或数组语法动态绑定 class 或 style:
:class="[baseClass, { active: isActive }]"
:style="{ backgroundColor: isActive ? 'green' : 'gray' }"
注意事项
- 确保每个按钮有唯一标识符(如 id 或 index)
- 考虑添加默认激活项(如设置
activeIndex: 0) - 移动端可添加触摸反馈样式
- 无障碍访问建议添加
aria-pressed属性







