vue实现选择联动
Vue 实现选择联动的方法
数据绑定与监听
在Vue中实现选择联动通常基于v-model和watch或computed属性。通过双向绑定第一个选择框的值,监听其变化动态更新第二个选择框的选项。
<template>
<div>
<select v-model="selectedProvince">
<option v-for="p in provinces" :value="p.id">{{ p.name }}</option>
</select>
<select v-model="selectedCity">
<option v-for="c in cities" :value="c.id">{{ c.name }}</option>
</select>
</div>
</template>
<script>
export default {
data() {
return {
provinces: [{id: 1, name: '广东'}, {id: 2, name: '江苏'}],
cities: [],
selectedProvince: null,
selectedCity: null
}
},
watch: {
selectedProvince(newVal) {
this.cities = this.getCitiesByProvince(newVal)
}
},
methods: {
getCitiesByProvince(provinceId) {
// 模拟根据省份获取城市
const cityData = {
1: [{id: 101, name: '广州'}, {id: 102, name: '深圳'}],
2: [{id: 201, name: '南京'}, {id: 202, name: '苏州'}]
}
return cityData[provinceId] || []
}
}
}
</script>
使用计算属性优化
对于简单的联动逻辑,计算属性比watch更简洁:
computed: {
filteredCities() {
return this.getCitiesByProvince(this.selectedProvince)
}
}
多级联动实现
三级联动(如省-市-区)可通过嵌套数据结构和多级监听实现:
watch: {
selectedProvince() {
this.cities = this.getCitiesByProvince(this.selectedProvince)
this.selectedCity = null
this.districts = []
},
selectedCity() {
this.districts = this.getDistrictsByCity(this.selectedCity)
}
}
异步数据加载
当选项数据需要从API获取时,使用async/await:
methods: {
async loadCities() {
this.cities = await axios.get(`/api/cities?province=${this.selectedProvince}`)
}
}
组件化封装
对于复用场景,可封装为独立组件:
<template>
<cascade-select
:levels="['province', 'city', 'district']"
@change="handleChange"
/>
</template>
注意事项
- 初始化时应设置默认选中项避免空值
- 清除下级选项时需重置
v-model绑定值 - 大数据量时考虑虚拟滚动优化性能
- 移动端可使用
<picker-view>等专用组件







