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>
</div>
</template>
<script>
export default {
data() {
return {
options: [
{ value: 'option1', label: 'Option 1' },
{ value: 'option2', label: 'Option 2' },
{ value: 'option3', label: 'Option 3' }
],
selectedOptions: []
}
}
}
</script>
动态生成多选条件
如果需要动态生成多选条件,可以通过遍历数据并绑定到复选框组实现。
<template>
<div>
<div v-for="condition in conditions" :key="condition.id">
<h4>{{ condition.name }}</h4>
<label v-for="item in condition.items" :key="item.id">
<input
type="checkbox"
v-model="selectedItems[condition.id]"
:value="item.id"
/>
{{ item.name }}
</label>
</div>
</div>
</template>
<script>
export default {
data() {
return {
conditions: [
{
id: 'category',
name: 'Category',
items: [
{ id: 'cat1', name: 'Category 1' },
{ id: 'cat2', name: 'Category 2' }
]
},
{
id: 'color',
name: 'Color',
items: [
{ id: 'red', name: 'Red' },
{ id: 'blue', name: 'Blue' }
]
}
],
selectedItems: {
category: [],
color: []
}
}
}
}
</script>
使用计算属性处理多选结果
通过计算属性可以方便地对多选结果进行过滤或处理。
<script>
export default {
computed: {
filteredResults() {
// 假设有一个数据列表需要根据多选条件过滤
const data = [...];
return data.filter(item => {
return (
(this.selectedItems.category.length === 0 ||
this.selectedItems.category.includes(item.category)) &&
(this.selectedItems.color.length === 0 ||
this.selectedItems.color.includes(item.color))
);
});
}
}
}
</script>
使用第三方组件库
如果需要更丰富的多选功能,可以集成第三方组件库如 Element UI 或 Vuetify。
Element UI 示例:
<template>
<el-checkbox-group v-model="selectedOptions">
<el-checkbox
v-for="option in options"
:key="option.value"
:label="option.value"
>
{{ option.label }}
</el-checkbox>
</el-checkbox-group>
</template>
Vuetify 示例:
<template>
<v-checkbox
v-for="option in options"
:key="option.value"
v-model="selectedOptions"
:value="option.value"
:label="option.label"
></v-checkbox>
</template>
多选与搜索结合
结合搜索功能可以实现动态过滤多选选项。
<template>
<div>
<input v-model="searchQuery" placeholder="Search options" />
<div v-for="option in filteredOptions" :key="option.value">
<input
type="checkbox"
v-model="selectedOptions"
:value="option.value"
/>
{{ option.label }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
searchQuery: '',
options: [...],
selectedOptions: []
}
},
computed: {
filteredOptions() {
return this.options.filter(option =>
option.label.toLowerCase().includes(this.searchQuery.toLowerCase())
);
}
}
}
</script>
以上方法涵盖了 Vue 中实现多条件多选的基本场景,可以根据具体需求进行调整或扩展。







