vue实现及联
Vue 实现级联选择
使用 Vue 实现级联选择可以通过多种方式完成,包括使用原生组件、第三方库或自定义实现。以下是几种常见方法:
使用 Element UI 的 Cascader 组件
Element UI 提供了 el-cascader 组件,支持级联选择功能。安装 Element UI 后可以直接使用:

<template>
<el-cascader
v-model="selectedOptions"
:options="options"
@change="handleChange"
></el-cascader>
</template>
<script>
export default {
data() {
return {
selectedOptions: [],
options: [
{
value: 'province1',
label: 'Province 1',
children: [
{
value: 'city1',
label: 'City 1'
}
]
}
]
};
},
methods: {
handleChange(value) {
console.log(value);
}
}
};
</script>
使用 Ant Design Vue 的 Cascader 组件
Ant Design Vue 也提供了级联选择组件 a-cascader,用法类似:

<template>
<a-cascader
v-model:value="selectedOptions"
:options="options"
@change="handleChange"
/>
</template>
<script>
export default {
data() {
return {
selectedOptions: [],
options: [
{
value: 'province1',
label: 'Province 1',
children: [
{
value: 'city1',
label: 'City 1'
}
]
}
]
};
},
methods: {
handleChange(value) {
console.log(value);
}
}
};
</script>
自定义级联选择
如果需要完全自定义级联选择逻辑,可以通过动态加载数据实现:
<template>
<div>
<select v-model="selectedProvince" @change="loadCities">
<option v-for="province in provinces" :value="province.id">
{{ province.name }}
</option>
</select>
<select v-model="selectedCity" @change="loadDistricts">
<option v-for="city in cities" :value="city.id">
{{ city.name }}
</option>
</select>
<select v-model="selectedDistrict">
<option v-for="district in districts" :value="district.id">
{{ district.name }}
</option>
</select>
</div>
</template>
<script>
export default {
data() {
return {
provinces: [],
cities: [],
districts: [],
selectedProvince: null,
selectedCity: null,
selectedDistrict: null
};
},
mounted() {
this.loadProvinces();
},
methods: {
loadProvinces() {
// 模拟 API 调用
this.provinces = [
{ id: 1, name: 'Province 1' },
{ id: 2, name: 'Province 2' }
];
},
loadCities() {
// 根据选中的省份加载城市
this.cities = [
{ id: 1, name: 'City 1' },
{ id: 2, name: 'City 2' }
];
},
loadDistricts() {
// 根据选中的城市加载区县
this.districts = [
{ id: 1, name: 'District 1' },
{ id: 2, name: 'District 2' }
];
}
}
};
</script>
动态加载数据
对于大数据量的级联选择,可以使用动态加载方式优化性能:
<template>
<el-cascader
v-model="selectedOptions"
:props="props"
></el-cascader>
</template>
<script>
export default {
data() {
return {
selectedOptions: [],
props: {
lazy: true,
lazyLoad(node, resolve) {
const { level } = node;
// 模拟异步加载
setTimeout(() => {
const nodes = Array.from({ length: 5 }).map((_, i) => ({
value: `${level}-${i}`,
label: `Option ${level}-${i}`,
leaf: level >= 2
}));
resolve(nodes);
}, 1000);
}
}
};
}
};
</script>
注意事项
- 数据格式需符合组件要求,通常为嵌套结构。
- 动态加载时注意性能优化,避免频繁请求。
- 对于复杂场景,可以结合后端 API 实现动态数据加载。
以上方法可以根据项目需求选择适合的实现方式。






