vue实现多选框
Vue 实现多选框的方法
在 Vue 中实现多选框可以通过多种方式,以下是几种常见的实现方法。
使用 v-model 绑定数组
Vue 的 v-model 可以绑定到一个数组,用于收集多选框的选中值。每个多选框的 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: 'option1', label: '选项1' },
{ value: 'option2', label: '选项2' },
{ value: 'option3', label: '选项3' },
],
selectedOptions: [],
};
},
};
</script>
使用 true-value 和 false-value
如果需要自定义多选框选中和未选中时的值,可以使用 true-value 和 false-value。
<template>
<div>
<input
type="checkbox"
v-model="checked"
:true-value="'选中'"
:false-value="'未选中'"
/>
<p>状态: {{ checked }}</p>
</div>
</template>
<script>
export default {
data() {
return {
checked: '未选中',
};
},
};
</script>
动态生成多选框组
结合 v-for 动态生成多选框组,适用于选项从后端获取的场景。
<template>
<div>
<label v-for="item in items" :key="item.id">
<input
type="checkbox"
v-model="selectedItems"
:value="item.id"
/>
{{ item.name }}
</label>
<p>选中的项目: {{ selectedItems }}</p>
</div>
</template>
<script>
export default {
data() {
return {
items: [
{ id: 1, name: '项目1' },
{ id: 2, name: '项目2' },
{ id: 3, name: '项目3' },
],
selectedItems: [],
};
},
};
</script>
使用计算属性处理选中状态
通过计算属性对多选框的选中状态进行逻辑处理。
<template>
<div>
<label v-for="fruit in fruits" :key="fruit.id">
<input
type="checkbox"
v-model="selectedFruits"
:value="fruit.id"
/>
{{ fruit.name }}
</label>
<p>选中的水果: {{ selectedFruitNames }}</p>
</div>
</template>
<script>
export default {
data() {
return {
fruits: [
{ id: 1, name: '苹果' },
{ id: 2, name: '香蕉' },
{ id: 3, name: '橙子' },
],
selectedFruits: [],
};
},
computed: {
selectedFruitNames() {
return this.fruits
.filter(fruit => this.selectedFruits.includes(fruit.id))
.map(fruit => fruit.name);
},
},
};
</script>
使用第三方组件库
如果需要更丰富的功能,可以使用第三方组件库如 Element UI、Vuetify 或 Ant Design Vue。
以 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>
以上方法覆盖了从基础到进阶的多选框实现方式,可以根据实际需求选择合适的方法。







