递归组件,实现无限级分类导航
https://cn.vuejs.org/v2/guide/components-edge-cases.html#递归组件
1、向后端请求数据,返回的数据结构长这样子
2、对后端返回的数据进行整理,整理为我们想要的结构,整理后数据结构长这样,如果有下级目录就添加children
最后递归组件,页面显示结果
父组件
HTML代码
<div> <synchronize-cell v-for="(item,index) in data" :synClass="item" :key="index"></synchronize-cell> </div>js代码
data(){ return{ data:[] } }, methods:{ //对后端返回的数据整理为我们想要的结构 treeData() { let tree = this.data.filter((father) => { //循环所有项 let branchArr = this.data.filter((child) => { return father.id == child.parentId //返回每一项的子级数组 }); if(branchArr.length > 0) { father.children = branchArr; //如果存在子级,则给父级添加一个children属性,并赋值 } return father.parentId == 0; //返回第一层 }); console.log(tree) this.data = tree //返回树形数据 }, }
子组件
<template> <div> <div class="courseWrapper" @click.stop="jumpRoute(synClass.type,synClass.courseId)"> <div class="courseTable" :class="synClass.type==0?'groupBorder':'courseBorder'"> <div class="clearfl titleStyle" :class="synClass.type==0?'titleBackStyle':''" :style="{paddingLeft:synClass.level*10+'px'}"> <div class="title">{{synClass.name}}</div> <div class="play" v-if="synClass.type==1">播放</div> </div> </div> <!-- 无限嵌套的重点就是在这里啦-判断是否有子节点,有的话就遍历子节点 --> <template v-if="synClass.children"> <synchronize-cell v-for="(item,index) in synClass.children" :synClass="item" :key="index"></synchronize-cell> </template> </div> </div> </template> <script> export default { name: "synchronize-cell", props: { synClass: { type: Object, default: function () { return {} } }, }, methods:{ jumpRoute(type,courseId){ console.log(courseId) if(type==0){ return }else { this.$router.push({ path:'/main/course/details', query:{ courseId:courseId } }) } } } } </script> <style scoped> .titleBackStyle { background-color: #f2f2f2; } .groupBorder{ border-bottom: 1px solid #e4e4e4; } .courseBorder{ border-bottom: 1px solid #f2f2f2; } .titleStyle { padding: 10px 0; padding-right: 10px; } .clearfl::after { display: block; content: ""; clear: both; } .groupName { background-color: #f2f2f2; padding: 10px 12px; border-bottom: 1px solid #e4e4e4; font-size: 14px; color: #515151; } .courseChild::after { display: block; content: ""; clear: both; } .title { float: left; } .play { float: right; } </style>
其他方法:https://www.cnblogs.com/duke-peng/p/8550321.html
转载于:https://www.cnblogs.com/YAN-HUA/p/9988878.html
相关资源:基于Vuejs编写的分类导航组件