vue实现关联选择显示
Vue 实现关联选择显示
关联选择显示通常指多个下拉菜单之间存在依赖关系,例如选择省份后动态加载城市列表。以下是实现方法:
数据绑定与监听
在Vue组件中定义响应式数据存储选项和选中值:
data() {
return {
provinces: [],
cities: [],
selectedProvince: null,
selectedCity: null
}
}
获取初始选项数据
在created或mounted钩子中初始化第一级选项:

async mounted() {
const res = await axios.get('/api/provinces')
this.provinces = res.data
}
监听第一级选择变化
使用watch监听第一级选择的变化,触发第二级选项加载:
watch: {
selectedProvince(newVal) {
if (newVal) {
this.loadCities(newVal)
this.selectedCity = null // 重置二级选择
}
}
},
methods: {
async loadCities(provinceId) {
const res = await axios.get(`/api/cities?province=${provinceId}`)
this.cities = res.data
}
}
模板渲染
使用v-model绑定选择值,v-for渲染选项:

<select v-model="selectedProvince">
<option v-for="p in provinces" :value="p.id">{{ p.name }}</option>
</select>
<select v-model="selectedCity" :disabled="!selectedProvince">
<option v-for="c in cities" :value="c.id">{{ c.name }}</option>
</select>
优化处理
添加加载状态和空状态提示:
<select v-model="selectedCity" :disabled="!selectedProvince || loading">
<option v-if="cities.length === 0" disabled>请先选择省份</option>
<option v-for="c in cities" :value="c.id">{{ c.name }}</option>
</select>
使用计算属性
对于复杂逻辑可以使用计算属性派生数据:
computed: {
filteredCities() {
return this.cities.filter(c => c.population > 1000000)
}
}
组件化方案
对于多处使用的关联选择,可以封装为独立组件:
Vue.component('cascade-select', {
props: ['levels'],
data() {
return {
selections: Array(this.levels.length).fill(null)
}
},
methods: {
handleSelect(index, value) {
this.$set(this.selections, index, value)
if (index < this.levels.length - 1) {
this.$emit('load', index + 1, value)
}
}
}
})






