vue实现级联
Vue 实现级联选择器的方法
级联选择器(Cascader)是常见的表单组件,用于处理多层级联动数据选择(如省市区选择)。以下是几种实现方式:

使用 Element UI 的 Cascader 组件
Element UI 提供了成熟的级联选择器组件,适用于 Vue 2 项目:

<template>
<el-cascader
v-model="selectedOptions"
:options="options"
@change="handleChange">
</el-cascader>
</template>
<script>
export default {
data() {
return {
selectedOptions: [],
options: [{
value: 'province1',
label: '省份1',
children: [{
value: 'city1',
label: '城市1'
}]
}]
};
},
methods: {
handleChange(value) {
console.log(value);
}
}
};
</script>
使用 Ant Design Vue 的 Cascader
Ant Design Vue 的级联组件适用于 Vue 3 或 Vue 2:
<template>
<a-cascader
v-model:value="selectedOptions"
:options="options"
placeholder="请选择"
/>
</template>
<script>
import { ref } from 'vue';
export default {
setup() {
const selectedOptions = ref([]);
const options = [
{
value: 'zhejiang',
label: '浙江',
children: [
{ value: 'hangzhou', label: '杭州' }
]
}
];
return { selectedOptions, options };
}
};
</script>
手动实现级联逻辑
若需完全自定义,可通过动态加载子选项实现:
<template>
<select v-model="selectedProvince" @change="loadCities">
<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>
</template>
<script>
export default {
data() {
return {
selectedProvince: null,
selectedCity: null,
provinces: [{ id: 1, name: '省份1' }],
cities: []
};
},
methods: {
loadCities() {
this.cities = this.getCitiesByProvince(this.selectedProvince);
}
}
};
</script>
关键注意事项
- 数据格式:级联数据通常为嵌套结构,需包含
value、label和children字段。 - 异步加载:对于大数据量,可通过
lazy属性和load方法实现按需加载。 - 表单验证:结合
v-model和验证库(如 VeeValidate)实现校验。
示例:异步加载实现
<el-cascader
:props="{
lazy: true,
lazyLoad(node, resolve) {
fetch(`/api/regions?parent=${node.value||0}`)
.then(res => resolve(res.data))
}
}"
/>
通过上述方法,可灵活实现不同场景下的级联选择需求。






