vue实现级联选择
Vue 实现级联选择的方法
使用 Element UI 的 Cascader 组件
Element UI 提供了一个现成的级联选择器组件,适用于大多数场景。安装 Element UI 后,可以直接使用 el-cascader 组件。
<template>
<el-cascader
v-model="selectedOptions"
:options="options"
:props="props"
@change="handleChange"
></el-cascader>
</template>
<script>
export default {
data() {
return {
selectedOptions: [],
options: [
{
value: 'province1',
label: 'Province 1',
children: [
{
value: 'city1',
label: 'City 1',
children: [
{
value: 'district1',
label: 'District 1'
}
]
}
]
}
],
props: {
expandTrigger: 'hover'
}
};
},
methods: {
handleChange(value) {
console.log(value);
}
}
};
</script>
使用 Ant Design Vue 的 Cascader 组件
Ant Design Vue 也提供了级联选择器组件,功能与 Element UI 类似。
<template>
<a-cascader
v-model:value="selectedOptions"
:options="options"
placeholder="Please select"
@change="handleChange"
/>
</template>
<script>
export default {
data() {
return {
selectedOptions: [],
options: [
{
value: 'province1',
label: 'Province 1',
children: [
{
value: 'city1',
label: 'City 1',
children: [
{
value: 'district1',
label: 'District 1'
}
]
}
]
}
]
};
},
methods: {
handleChange(value) {
console.log(value);
}
}
};
</script>
自定义级联选择器
如果需要更灵活的级联选择器,可以手动实现。以下是一个简单的自定义级联选择器示例。
<template>
<div>
<select v-model="selectedProvince" @change="loadCities">
<option v-for="province in provinces" :value="province.value">
{{ province.label }}
</option>
</select>
<select v-model="selectedCity" @change="loadDistricts" v-if="cities.length">
<option v-for="city in cities" :value="city.value">
{{ city.label }}
</option>
</select>
<select v-model="selectedDistrict" v-if="districts.length">
<option v-for="district in districts" :value="district.value">
{{ district.label }}
</option>
</select>
</div>
</template>
<script>
export default {
data() {
return {
selectedProvince: '',
selectedCity: '',
selectedDistrict: '',
provinces: [
{ value: 'province1', label: 'Province 1' }
],
cities: [],
districts: []
};
},
methods: {
loadCities() {
this.cities = [
{ value: 'city1', label: 'City 1' }
];
this.selectedCity = '';
this.selectedDistrict = '';
this.districts = [];
},
loadDistricts() {
this.districts = [
{ value: 'district1', label: 'District 1' }
];
this.selectedDistrict = '';
}
}
};
</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: level + 1 })
.map((_, i) => ({
value: `${level}-${i}`,
label: `Option ${level}-${i}`,
leaf: level >= 2
}));
resolve(nodes);
}, 1000);
}
}
};
}
};
</script>
注意事项
- 数据格式必须符合组件要求,通常是一个嵌套的数组结构。
- 动态加载数据时,注意处理加载状态和错误情况。
- 如果需要更复杂的功能,可以结合后端 API 动态获取数据。







