vue的递归组件以及三级菜单的制作
js 里面有递归算法,同时,我们也可以利用 props 来实现 vue 模板的递归调用,但是前提是组件拥有 name 属性
父组件:slotDemo.vue:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | < template > < div > <!-----递归组件-----> < ul > < simple3 :tree="item" v-for="item in tree"></ simple3 > </ ul > </ div > </ template > < style lang="stylus" rel="stylesheet/stylus"> li padding-left 30px </ style > < script > import simple3 from "./simple/simple3.vue"; export default{ data(){ return { tree: [{ label: "一级菜单", test:1, children: [{ label: "二级菜单", test:2, children: [{ label: "三级菜单", test:3 }] }] }] } }, components: { simple3 } } </ script > |
子组件:simple3.vue
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | < template > < li > < a >{{tree.label}}</ a > < simple3 v-if="tree.children" :tree="item" v-for="item in tree.children" :class="item.test==2?'test2':'test3'"></ simple3 > </ li > </ template > < style rel="stylesheet/stylus" lang="stylus"> .test2 list-style disc .test3 list-style decimal </ style > < script > export default{ name: "simple3", props: ["tree"] } </ script > |
上面是一个子组件,定义了 name 为 simple03,然后在模板中调用自身,结合 v-for 实现递归
为了防止出现死循环,在调用自身的时候,加入了 v-if 作为判定条件
父组件中调用的时候,需要通过 props 传入一个 tree;
为了对每一级菜单有所区分,我对 tree 里面的每一个子集合里面加了一个 test 字段来区分是哪一级的菜单然后对其不同的样式进行处理
最后的效果: