vue按钮实现单选全选
实现单选和全选功能的 Vue 按钮
在 Vue 中实现单选和全选功能,通常需要结合 v-model 和计算属性来管理选中状态。以下是具体实现方法:

单选功能实现
单选功能可以通过 v-model 绑定到单个变量,或者通过数组管理多个选项的选中状态。

<template>
<div>
<label v-for="option in options" :key="option.value">
<input
type="radio"
v-model="selectedOption"
:value="option.value"
>
{{ option.label }}
</label>
</div>
</template>
<script>
export default {
data() {
return {
selectedOption: '',
options: [
{ value: 'option1', label: 'Option 1' },
{ value: 'option2', label: 'Option 2' },
{ value: 'option3', label: 'Option 3' }
]
}
}
}
</script>
全选功能实现
全选功能通常用于多选框场景,需要一个数组来存储选中的值,并通过计算属性判断是否全选。
<template>
<div>
<label>
<input
type="checkbox"
v-model="selectAll"
@change="toggleSelectAll"
>
Select All
</label>
<label v-for="item in items" :key="item.id">
<input
type="checkbox"
v-model="selectedItems"
:value="item.id"
>
{{ item.name }}
</label>
</div>
</template>
<script>
export default {
data() {
return {
selectedItems: [],
items: [
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' },
{ id: 3, name: 'Item 3' }
]
}
},
computed: {
selectAll: {
get() {
return this.selectedItems.length === this.items.length
},
set(value) {
this.selectedItems = value ? this.items.map(item => item.id) : []
}
}
},
methods: {
toggleSelectAll() {
this.selectAll = !this.selectAll
}
}
}
</script>
结合单选和全选
如果需要同时支持单选和全选,可以根据业务逻辑调整实现方式。
<template>
<div>
<label>
<input
type="checkbox"
v-model="allSelected"
@change="handleSelectAll"
>
Select All
</label>
<label v-for="option in options" :key="option.value">
<input
type="checkbox"
v-model="selectedOptions"
:value="option.value"
@change="handleSingleSelect"
>
{{ option.label }}
</label>
</div>
</template>
<script>
export default {
data() {
return {
allSelected: false,
selectedOptions: [],
options: [
{ value: 'option1', label: 'Option 1' },
{ value: 'option2', label: 'Option 2' },
{ value: 'option3', label: 'Option 3' }
]
}
},
methods: {
handleSelectAll() {
this.selectedOptions = this.allSelected
? this.options.map(opt => opt.value)
: []
},
handleSingleSelect() {
this.allSelected = this.selectedOptions.length === this.options.length
}
}
}
</script>
关键点说明
- 单选功能使用
type="radio"的输入框,通过v-model绑定到单个变量。 - 全选功能使用
type="checkbox"的输入框,通过计算属性和方法动态更新选中状态。 - 结合单选和全选时,需要注意状态同步,确保 UI 和数据的双向绑定正确。






