vue实现选项排他
Vue实现选项排他逻辑
使用Vue实现选项排他(即单选效果)可以通过数据绑定和事件监听实现。以下是几种常见方法:
使用v-model绑定
通过v-model绑定到同一个变量,天然实现排他效果:
<template>
<div>
<input type="radio" id="option1" value="option1" v-model="selectedOption">
<label for="option1">选项1</label>
<input type="radio" id="option2" value="option2" v-model="selectedOption">
<label for="option2">选项2</label>
</div>
</template>
<script>
export default {
data() {
return {
selectedOption: ''
}
}
}
</script>
使用自定义逻辑
对于非radio元素(如按钮),可通过计算属性或方法实现:
<template>
<div>
<button
v-for="option in options"
:key="option.value"
@click="selectOption(option.value)"
:class="{ active: selectedOption === option.value }"
>
{{ option.label }}
</button>
</div>
</template>
<script>
export default {
data() {
return {
options: [
{ value: 'opt1', label: '选项1' },
{ value: 'opt2', label: '选项2' }
],
selectedOption: null
}
},
methods: {
selectOption(value) {
this.selectedOption = value
}
}
}
</script>
使用Vuex状态管理
当需要跨组件共享选择状态时:
// store.js
export default new Vuex.Store({
state: {
selectedOption: null
},
mutations: {
setOption(state, payload) {
state.selectedOption = payload
}
}
})
<template>
<button @click="$store.commit('setOption', 'opt1')">选项1</button>
</template>
动态选项排他实现
对于动态生成的选项列表,可以使用v-for结合上述方法:
<template>
<div>
<div
v-for="item in items"
:key="item.id"
@click="selectItem(item.id)"
:class="{ selected: selectedId === item.id }"
>
{{ item.text }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
items: [
{ id: 1, text: '动态选项1' },
{ id: 2, text: '动态选项2' }
],
selectedId: null
}
},
methods: {
selectItem(id) {
this.selectedId = id === this.selectedId ? null : id
}
}
}
</script>
表单验证集成
结合Vuelidate等验证库实现带验证的排他选择:
import { required } from 'vuelidate/lib/validators'
export default {
validations: {
selectedOption: { required }
}
}
以上方法均可根据实际场景组合使用,关键点在于维护单一数据源并通过响应式更新UI状态。







