vue实现列表多选
Vue 实现列表多选的方法
使用 v-model 绑定数组
通过 v-model 绑定一个数组,可以轻松实现多选功能。当复选框被选中或取消选中时,数组会自动更新。
<template>
<div>
<div v-for="item in items" :key="item.id">
<input
type="checkbox"
:id="item.id"
:value="item.value"
v-model="selectedItems"
>
<label :for="item.id">{{ item.label }}</label>
</div>
<p>已选中的项: {{ selectedItems }}</p>
</div>
</template>
<script>
export default {
data() {
return {
items: [
{ id: 1, label: '选项1', value: 'value1' },
{ id: 2, label: '选项2', value: 'value2' },
{ id: 3, label: '选项3', value: 'value3' },
],
selectedItems: []
};
}
};
</script>
使用 v-for 渲染多选列表
结合 v-for 动态渲染列表,并为每个选项绑定 v-model 到数组。
<template>
<div>
<ul>
<li v-for="option in options" :key="option.id">
<input
type="checkbox"
v-model="selectedOptions"
:value="option.id"
>
{{ option.text }}
</li>
</ul>
<p>选中的选项 ID: {{ selectedOptions }}</p>
</div>
</template>
<script>
export default {
data() {
return {
options: [
{ id: 1, text: '选项A' },
{ id: 2, text: '选项B' },
{ id: 3, text: '选项C' },
],
selectedOptions: []
};
}
};
</script>
使用第三方组件库
如果需要更丰富的功能(如全选、反选等),可以使用第三方组件库如 Element UI 或 Vuetify。
以 Element UI 为例:
<template>
<div>
<el-checkbox-group v-model="checkedCities">
<el-checkbox
v-for="city in cities"
:label="city"
:key="city"
>
{{ city }}
</el-checkbox>
</el-checkbox-group>
<p>选中的城市: {{ checkedCities }}</p>
</div>
</template>
<script>
export default {
data() {
return {
cities: ['北京', '上海', '广州', '深圳'],
checkedCities: []
};
}
};
</script>
自定义多选逻辑
如果需要更复杂的逻辑(如动态禁用某些选项),可以手动处理选中状态。
<template>
<div>
<div v-for="item in items" :key="item.id">
<input
type="checkbox"
:checked="isSelected(item.id)"
@change="toggleSelection(item.id)"
:disabled="item.disabled"
>
<label>{{ item.name }}</label>
</div>
<p>选中的 ID: {{ selectedIds }}</p>
</div>
</template>
<script>
export default {
data() {
return {
items: [
{ id: 1, name: '苹果', disabled: false },
{ id: 2, name: '香蕉', disabled: true },
{ id: 3, name: '橙子', disabled: false },
],
selectedIds: []
};
},
methods: {
isSelected(id) {
return this.selectedIds.includes(id);
},
toggleSelection(id) {
const index = this.selectedIds.indexOf(id);
if (index === -1) {
this.selectedIds.push(id);
} else {
this.selectedIds.splice(index, 1);
}
}
}
};
</script>
注意事项
- 确保
v-model绑定的数组初始化为空数组。 - 动态绑定时,注意
:value的值类型(字符串、数字或对象)。 - 如果需要禁用某些选项,可以通过
:disabled属性控制。







