vue排他思想实现
Vue 排他思想实现
排他思想在 Vue 中通常指多个元素中只能有一个被选中或激活的状态。可以通过数据驱动和条件渲染实现。
使用 v-model 和计算属性
定义一个数据属性存储当前选中项的索引或标识,通过 v-model 或事件绑定更新选中状态。
<template>
<div>
<button
v-for="(item, index) in items"
:key="index"
@click="selectItem(index)"
:class="{ active: selectedIndex === index }"
>
{{ item }}
</button>
</div>
</template>
<script>
export default {
data() {
return {
items: ['选项1', '选项2', '选项3'],
selectedIndex: -1
}
},
methods: {
selectItem(index) {
this.selectedIndex = index
}
}
}
</script>
<style>
.active {
background-color: #42b983;
color: white;
}
</style>
使用组件状态管理
通过 Vuex 或 Pinia 管理全局状态,实现跨组件排他选择。
// Pinia 示例
import { defineStore } from 'pinia'
export const useSelectionStore = defineStore('selection', {
state: () => ({
selectedId: null
}),
actions: {
setSelected(id) {
this.selectedId = id
}
}
})
动态样式绑定
利用 :class 或 :style 动态绑定样式,通过条件判断实现视觉排他效果。
<template>
<div>
<div
v-for="item in list"
:class="['item', { 'selected': item.id === activeId }]"
@click="activeId = item.id"
>
{{ item.name }}
</div>
</div>
</template>
表单元素排他选择
对于单选按钮组,直接使用 v-model 绑定同一变量即可实现原生排他选择。
<template>
<div>
<input type="radio" id="option1" value="1" v-model="selectedOption">
<label for="option1">选项1</label>
<input type="radio" id="option2" value="2" v-model="selectedOption">
<label for="option2">选项2</label>
</div>
</template>
注意事项
- 确保每次操作后只更新一个选中状态
- 对于复杂场景,建议使用状态管理工具
- 列表渲染时需设置唯一
key保证性能 - 移动端注意增加点击反馈效果







