vue实现多级select表单
Vue 多级 Select 表单实现方案
方案一:基于递归组件实现
创建递归组件处理无限层级数据
<template>
<select v-model="selectedValue" @change="handleChange">
<option value="">请选择</option>
<option
v-for="item in options"
:key="item.value"
:value="item.value"
>
{{ item.label }}
</option>
</select>
<child-select
v-if="hasChildren"
:options="currentChildren"
@change="handleChildChange"
/>
</template>
<script>
export default {
name: 'ChildSelect',
props: ['options'],
data() {
return {
selectedValue: '',
currentChildren: []
}
},
computed: {
hasChildren() {
return this.currentChildren.length > 0
}
},
methods: {
handleChange(event) {
const selected = this.options.find(item => item.value === event.target.value)
this.currentChildren = selected?.children || []
this.$emit('change', event)
}
}
}
</script>
方案二:使用现成组件库
Element UI 级联选择器
<template>
<el-cascader
:options="options"
:props="{ checkStrictly: true }"
clearable
/>
</template>
<script>
export default {
data() {
return {
options: [{
value: '1',
label: '一级',
children: [{
value: '1-1',
label: '二级'
}]
}]
}
}
}
</script>
方案三:动态加载选项
适用于大数据量的异步加载场景
<template>
<select v-model="level1" @change="loadLevel2">
<option v-for="item in level1Options" :value="item.id">{{ item.name }}</option>
</select>
<select v-model="level2" @change="loadLevel3" v-if="level2Options.length">
<option v-for="item in level2Options" :value="item.id">{{ item.name }}</option>
</select>
<select v-model="level3" v-if="level3Options.length">
<option v-for="item in level3Options" :value="item.id">{{ item.name }}</option>
</select>
</template>
<script>
export default {
data() {
return {
level1: '',
level2: '',
level3: '',
level1Options: [],
level2Options: [],
level3Options: []
}
},
methods: {
async loadLevel2() {
this.level2Options = await fetchOptions(this.level1)
},
async loadLevel3() {
this.level3Options = await fetchOptions(this.level2)
}
}
}
</script>
实现注意事项
数据格式规范建议
const options = [
{
value: '1',
label: '一级选项',
children: [
{
value: '1-1',
label: '二级选项'
}
]
}
]
性能优化建议
对于大型数据集考虑虚拟滚动技术 使用watch监听选择变化而非直接绑定事件 复杂场景建议使用Vuex管理状态
移动端适配方案
使用picker组件替代原生select 考虑添加搜索过滤功能 支持手势滑动选择
以上方案可根据实际项目需求进行组合或调整,递归组件适合不确定层级深度的场景,组件库方案开发效率最高,动态加载适合性能敏感型应用。







