vue实现多级联动
vue实现多级联动的方法
多级联动通常指多个下拉菜单之间存在依赖关系,例如省市区三级联动。以下是几种实现方式:
基于v-model和watch实现
通过v-model绑定数据,watch监听变化触发下级数据更新:
<template>
<select v-model="province" @change="loadCities">
<option v-for="p in provinces" :value="p.id">{{p.name}}</option>
</select>
<select v-model="city" @change="loadAreas">
<option v-for="c in cities" :value="c.id">{{c.name}}</option>
</select>
<select v-model="area">
<option v-for="a in areas" :value="a.id">{{a.name}}</option>
</select>
</template>
<script>
export default {
data() {
return {
province: '',
city: '',
area: '',
provinces: [],
cities: [],
areas: []
}
},
methods: {
loadCities() {
this.cities = getCitiesByProvince(this.province)
this.city = ''
this.areas = []
},
loadAreas() {
this.areas = getAreasByCity(this.city)
this.area = ''
}
}
}
</script>
使用计算属性实现
利用计算属性自动响应数据变化:
computed: {
cities() {
return this.province ? getCitiesByProvince(this.province) : []
},
areas() {
return this.city ? getAreasByCity(this.city) : []
}
}
使用第三方组件库
Element UI等库提供现成的级联选择器:
<template>
<el-cascader
v-model="selected"
:options="options"
@change="handleChange">
</el-cascader>
</template>
递归组件实现无限级联动
对于不确定层级的情况,可使用递归组件:
<template>
<select v-model="currentValue" @change="onChange">
<option v-for="item in options" :value="item.id">{{item.name}}</option>
</select>
<child-select
v-if="childrenOptions.length"
:options="childrenOptions"
@input="onChildInput"
/>
</template>
<script>
export default {
name: 'ChildSelect',
props: ['options'],
data() {
return {
currentValue: '',
childrenOptions: []
}
},
methods: {
onChange() {
this.childrenOptions = getChildren(this.currentValue)
this.$emit('input', this.currentValue)
},
onChildInput(val) {
this.$emit('input', val)
}
}
}
</script>
使用Vuex管理状态
对于复杂应用,建议使用Vuex集中管理联动数据:
// store.js
const store = new Vuex.Store({
state: {
province: null,
city: null,
area: null
},
mutations: {
setProvince(state, val) {
state.province = val
state.city = null
state.area = null
}
}
})
注意事项
- 初始加载时需要清空下级选项
- 处理异步数据加载时的loading状态
- 考虑添加默认提示选项如"请选择"
- 对于大数据量考虑虚拟滚动优化性能
以上方法可根据具体场景组合使用,简单联动推荐使用计算属性方式,复杂场景建议使用Vuex+组件化方案。







