vue实现多选联动
Vue 实现多选联动的方法
多选联动通常指一组复选框或下拉菜单的选择状态相互影响,常见于级联选择或依赖关系的场景。以下是几种实现方式:
使用 v-model 和计算属性
通过 v-model 绑定数据,结合计算属性处理联动逻辑:
<template>
<div>
<label v-for="option in options" :key="option.id">
<input
type="checkbox"
v-model="selectedOptions"
:value="option.id"
>
{{ option.name }}
</label>
</div>
</template>
<script>
export default {
data() {
return {
options: [
{ id: 1, name: '选项1' },
{ id: 2, name: '选项2' },
{ id: 3, name: '选项3' }
],
selectedOptions: []
};
},
computed: {
// 联动逻辑示例:选中选项1时自动选中选项2
processedSelection() {
if (this.selectedOptions.includes(1) && !this.selectedOptions.includes(2)) {
return [...this.selectedOptions, 2];
}
return this.selectedOptions;
}
},
watch: {
processedSelection(newVal) {
this.selectedOptions = newVal;
}
}
};
</script>
使用事件处理联动
通过 @change 事件手动处理联动逻辑:
<template>
<div>
<label>
<input
type="checkbox"
v-model="option1"
@change="handleOption1Change"
>
选项1
</label>
<label>
<input
type="checkbox"
v-model="option2"
:disabled="!option1"
>
选项2(依赖选项1)
</label>
</div>
</template>
<script>
export default {
data() {
return {
option1: false,
option2: false
};
},
methods: {
handleOption1Change() {
if (!this.option1) {
this.option2 = false;
}
}
}
};
</script>
使用第三方组件库
若使用 Element UI 等库,可直接利用其级联选择组件:
<template>
<el-cascader
:options="options"
v-model="selectedOptions"
:props="{ multiple: true }"
></el-cascader>
</template>
<script>
export default {
data() {
return {
options: [{
value: 'guide',
label: '指南',
children: [{
value: 'design',
label: '设计'
}]
}],
selectedOptions: []
};
}
};
</script>
动态渲染联动选项
根据前一个选择的结果动态加载后续选项:
<template>
<div>
<select v-model="selectedCategory" @change="loadSubOptions">
<option v-for="cat in categories" :value="cat.id">{{ cat.name }}</option>
</select>
<select v-model="selectedSubOption" :disabled="!selectedCategory">
<option v-for="item in subOptions" :value="item.id">{{ item.name }}</option>
</select>
</div>
</template>
<script>
export default {
data() {
return {
categories: [{ id: 1, name: '分类1' }],
subOptions: [],
selectedCategory: null,
selectedSubOption: null
};
},
methods: {
loadSubOptions() {
// 根据 selectedCategory 异步加载 subOptions
this.subOptions = [{ id: 101, name: '子项1' }];
}
}
};
</script>
关键注意事项
- 双向绑定数据需明确初始化,避免未定义导致的错误
- 联动逻辑应考虑边界条件,如全选、反选或部分禁用
- 性能优化:大量数据时建议分页或虚拟滚动
- 可结合 Vuex 管理复杂状态
以上方法可根据实际场景组合使用,实现灵活的多级联动效果。







