vue解决Element-ui中 el-cascader 级联选择器 最后一级数据为空显示暂无数据问题

1. 出现问题bug: el-cascader控件 最后一级出现空白 暂无数据

在这里插入图片描述

2. 问题原因分析:

经过调试分析出现空级联原因是:由于数据是从后台传递过来的,当后端的哥们使用递归算出菜单,然后转换成json传递到前端的时候。就会出现 最底层 的子项中 的 children 为空数组,这样就会造成,空级联 的bug存在。


在这里插入图片描述

3. 解决办法: 使用递归的方式,将最底层中的 children设为undefined

3.1 html 代码

<el-cascader
  :show-all-levels="false"
  v-model="subCatValue"
  :options="allSubCatList"
  :props="optionProps"
  @change="handleSubCat"
></el-cascader>

3.2 JS处理 代码

  • 主要是 getTreeData 方法递归判断
  • el-cascader 的 optionProps 属性可以根据后端的返回值映射为识别的对应值
export default {
  data() {
    return {
      optionProps: {
        value: 'id',
        label: 'className',
        children: 'subcat'
      },// 格式化工单信息
      allSubCatList:[], // 工单分类列表
      subCatValue:[], // 工单分类值
      },
    };
  },
  methods: {
  	// 获取列表
    getAllSubCatList(){
      this.$axios.get(this.$httpServer.getAllSubCatList,{}).then((res)=>{
        console.log(res);
        if(res.status == "200"){
          this.allSubCatList = this.getTreeData(res.data.data);
        }
      })
    },
    // 递归判断列表,把最后的children设为undefined
    getTreeData(data){
      for(var i=0;i<data.length;i++){
        if(data[i].subcat.length<1){
          // children若为空数组,则将children设为undefined
          data[i].subcat=undefined;
        }else {
          // children若不为空数组,则继续 递归调用 本方法
          this.getTreeData(data[i].subcat);
        }
      }
      return data;
    }
  },
};
</script>

4. 解决后效果:

在这里插入图片描述

发布了109 篇原创文章 · 获赞 91 · 访问量 33万+

猜你喜欢

转载自blog.csdn.net/qq_36410795/article/details/97492512
今日推荐