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>
动态生成多选条件
如果需要根据后端数据或用户输入动态生成多选条件,可以结合 v-for 和计算属性实现。
<template>
<div>
<div v-for="category in categories" :key="category.id">
<h3>{{ category.name }}</h3>
<label v-for="item in category.items" :key="item.id">
<input
type="checkbox"
v-model="selectedItems"
:value="item.id"
>
{{ item.name }}
</label>
</div>
</div>
</template>
<script>
export default {
data() {
return {
categories: [
{
id: 1,
name: '颜色',
items: [
{ id: 'red', name: '红色' },
{ id: 'blue', name: '蓝色' }
]
},
{
id: 2,
name: '尺寸',
items: [
{ id: 's', name: '小号' },
{ id: 'l', name: '大号' }
]
}
],
selectedItems: []
};
}
};
</script>
多条件筛选逻辑
实现多条件筛选时,可以通过计算属性对数据进行过滤。以下是一个结合多选条件筛选列表的例子。
<template>
<div>
<div>
<h3>筛选条件</h3>
<label v-for="filter in filters" :key="filter.id">
<input
type="checkbox"
v-model="activeFilters"
:value="filter.id"
>
{{ filter.name }}
</label>
</div>
<ul>
<li v-for="item in filteredItems" :key="item.id">
{{ item.name }}
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
filters: [
{ id: 'featured', name: '精选' },
{ id: 'new', name: '新品' }
],
activeFilters: [],
items: [
{ id: 1, name: '商品1', tags: ['featured'] },
{ id: 2, name: '商品2', tags: ['new'] },
{ id: 3, name: '商品3', tags: ['featured', 'new'] }
]
};
},
computed: {
filteredItems() {
if (this.activeFilters.length === 0) {
return this.items;
}
return this.items.filter(item =>
this.activeFilters.every(filter =>
item.tags.includes(filter)
)
);
}
}
};
</script>
使用第三方组件库
如果需要更丰富的多选功能(如搜索、分组等),可以集成第三方组件库如 Element UI 或 Vuetify。
以 Element UI 为例:
<template>
<div>
<el-checkbox-group v-model="checkedCities">
<el-checkbox
v-for="city in cities"
:key="city"
:label="city"
>
{{ city }}
</el-checkbox>
</el-checkbox-group>
</div>
</template>
<script>
export default {
data() {
return {
cities: ['北京', '上海', '广州', '深圳'],
checkedCities: []
};
}
};
</script>
注意事项
- 确保多选框的
value唯一,避免重复值导致状态混乱。 - 如果选项数据来自后端,需处理异步加载时的初始状态。
- 对于大量选项,考虑添加搜索或分页功能优化体验。







