vue实现多选框
基础实现
使用 v-model 绑定数组实现多选功能。在 Vue 中,多选框的 value 属性会随选中状态自动更新到绑定的数组。
<template>
<div>
<label v-for="option in options" :key="option.value">
<input
type="checkbox"
v-model="selectedOptions"
:value="option.value"
>
{{ 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>
动态渲染选项
通过 v-for 动态渲染多选框选项,适合从 API 获取数据的场景。
<template>
<div>
<div v-for="item in dynamicOptions" :key="item.id">
<input
type="checkbox"
v-model="checkedItems"
:value="item.id"
>
{{ item.name }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
dynamicOptions: [
{ id: 1, name: '选项A' },
{ id: 2, name: '选项B' },
{ id: 3, name: '选项C' }
],
checkedItems: []
}
}
}
</script>
全选功能
添加全选按钮逻辑,通过计算属性实现一键全选或取消。
<template>
<div>
<input type="checkbox" v-model="selectAll"> 全选
<div v-for="item in items" :key="item.id">
<input
type="checkbox"
v-model="selectedIds"
:value="item.id"
>
{{ item.text }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
items: [
{ id: 1, text: '项目1' },
{ id: 2, text: '项目2' },
{ id: 3, text: '项目3' }
],
selectedIds: []
}
},
computed: {
selectAll: {
get() {
return this.selectedIds.length === this.items.length
},
set(value) {
this.selectedIds = value
? this.items.map(item => item.id)
: []
}
}
}
}
</script>
组件封装
封装可复用的多选框组件,通过 props 接收选项,通过 emit 返回选中值。
<!-- CheckboxGroup.vue -->
<template>
<div class="checkbox-group">
<label v-for="option in options" :key="option.value">
<input
type="checkbox"
:value="option.value"
v-model="internalValue"
>
{{ option.label }}
</label>
</div>
</template>
<script>
export default {
props: {
options: {
type: Array,
required: true
},
value: {
type: Array,
default: () => []
}
},
computed: {
internalValue: {
get() {
return this.value
},
set(val) {
this.$emit('input', val)
}
}
}
}
</script>
样式优化
使用 CSS 美化多选框,常见方案包括隐藏原生输入框,用伪元素自定义样式。
.checkbox-container {
position: relative;
padding-left: 25px;
cursor: pointer;
}
.checkbox-container input {
position: absolute;
opacity: 0;
}
.checkmark {
position: absolute;
top: 0;
left: 0;
height: 18px;
width: 18px;
background-color: #eee;
border-radius: 4px;
}
.checkbox-container:hover .checkmark {
background-color: #ccc;
}
.checkbox-container input:checked ~ .checkmark {
background-color: #2196F3;
}
.checkmark:after {
content: "";
position: absolute;
display: none;
}
.checkbox-container input:checked ~ .checkmark:after {
display: block;
}
.checkbox-container .checkmark:after {
left: 6px;
top: 2px;
width: 5px;
height: 10px;
border: solid white;
border-width: 0 2px 2px 0;
transform: rotate(45deg);
}






