vue 实现多选框
实现多选框的基本方法
在 Vue 中实现多选框可以通过 v-model 指令绑定到数组,监听用户选择的选项。以下是一个基础实现示例:
<template>
<div>
<label v-for="option in options" :key="option.value">
<input
type="checkbox"
:value="option.value"
v-model="selectedOptions"
>
{{ option.label }}
</label>
<p>已选择: {{ selectedOptions }}</p>
</div>
</template>
<script>
export default {
data() {
return {
options: [
{ value: 'apple', label: '苹果' },
{ value: 'banana', label: '香蕉' },
{ value: 'orange', label: '橘子' }
],
selectedOptions: []
}
}
}
</script>
动态生成多选框
如果需要从 API 或动态数据生成多选框,可以结合 v-for 指令遍历数据:

<template>
<div>
<div v-for="item in dynamicOptions" :key="item.id">
<input
type="checkbox"
:id="'checkbox-' + item.id"
:value="item.id"
v-model="checkedItems"
>
<label :for="'checkbox-' + item.id">{{ item.name }}</label>
</div>
</div>
</template>
<script>
export default {
data() {
return {
dynamicOptions: [],
checkedItems: []
}
},
async created() {
this.dynamicOptions = await fetchOptionsFromAPI()
}
}
</script>
全选/反选功能实现
添加全选功能可以通过计算属性和方法结合实现:

<template>
<div>
<input type="checkbox" v-model="selectAll" @change="toggleSelectAll">
全选
<div v-for="option in options" :key="option.value">
<input
type="checkbox"
:value="option.value"
v-model="selectedOptions"
>
{{ option.label }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
options: [/* 选项数据 */],
selectedOptions: []
}
},
computed: {
selectAll: {
get() {
return this.selectedOptions.length === this.options.length
},
set(value) {
this.selectedOptions = value
? this.options.map(opt => opt.value)
: []
}
}
},
methods: {
toggleSelectAll() {
this.selectAll = !this.selectAll
}
}
}
</script>
使用第三方组件库
对于更复杂的需求,可以使用 UI 组件库如 Element UI 的多选框组件:
<template>
<el-checkbox-group v-model="checkedCities">
<el-checkbox v-for="city in cities" :label="city" :key="city">
{{ city }}
</el-checkbox>
</el-checkbox-group>
</template>
<script>
export default {
data() {
return {
cities: ['上海', '北京', '广州', '深圳'],
checkedCities: []
}
}
}
</script>
表单验证处理
结合 Vue 的表单验证库如 VeeValidate 实现多选框验证:
<template>
<ValidationObserver v-slot="{ handleSubmit }">
<form @submit.prevent="handleSubmit(onSubmit)">
<ValidationProvider
name="选项"
rules="required"
v-slot="{ errors }"
>
<div v-for="option in options" :key="option.value">
<input
type="checkbox"
:value="option.value"
v-model="selectedOptions"
>
{{ option.label }}
</div>
<span class="error">{{ errors[0] }}</span>
</ValidationProvider>
<button type="submit">提交</button>
</form>
</ValidationObserver>
</template>
以上方法涵盖了 Vue 中实现多选框的常见场景,从基础实现到高级功能,开发者可以根据实际需求选择适合的方式。






