1、级联下拉框的标题和值设置

<el-form-item label="商品类型" prop="categoryId">
<el-cascader
v-model="form.categoryId"
:options="categoryTree"
:props="{ label: 'categoryName', value: 'categoryId', emitPath: false }"
@change="handleCategoryTreeChange"></el-cascader>
</el-form-item>
- 设置前

- 设置后

2、解决无法选择问题
问题描述:
级联下拉框,最后一级无法选择的问题。
问题原因:
是由于属性children是空数组,解决的办法是把children设为null或者直接删掉。
解决思路:
定义一个函数,删除children为空数据的属性。
- 代码片段1(定义函数)
// 递归去除空的 children 属性
removeEmptyChildren(obj) {
if (!obj || typeof obj !== 'object') {
return obj
}
// 处理数组
if (Array.isArray(obj)) {
return obj
.map(item => this.removeEmptyChildren(item))
.filter(item => item !== null && item !== undefined)
}
// 处理对象
const newObj = {}
for (const [key, value] of Object.entries(obj)) {
// 如果是 children 且为空数组,则跳过
if (key === 'children' && Array.isArray(value) && value.length === 0) {
continue
}
// 递归处理值
const processedValue = this.removeEmptyChildren(value)
// 如果处理后的值不是 null/undefined,则添加到新对象
if (processedValue !== null && processedValue !== undefined) {
// 对于非 children 属性,或者 children 有内容的情况,保留
if (key !== 'children' || (Array.isArray(processedValue) && processedValue.length > 0)) {
newObj[key] = processedValue
}
}
}
return newObj
},
- 代码片段2(调用函数)
/** 查询商品分类列表 */
getCategoryList() {
listCategory(this.queryParams).then(response => {
this.categoryList = response.data;
this.categoryTree = this.handleTree(this.categoryList, "categoryId", "parentId")
this.categoryTree = this.removeEmptyChildren(this.categoryTree);
console.log(this.categoryTree);
})
},
3、级联下拉框的值为数据的问题
只需要给级联下拉框添加 emitPath: false 属性即可,具体代码如下:
<el-form-item label="商品类型" prop="categoryId">
<el-cascader
v-model="form.categoryId"
:options="categoryTree"
:props="{ label: 'categoryName', value: 'categoryId', emitPath: false }"
@change="handleCategoryTreeChange"></el-cascader>
</el-form-item>