组件的无限嵌套,相信大家在一些场景中应该都会用到,比如侧边栏导航、树形结构等等,今天我就来说下怎么实现组件的无限嵌套吧,很easy!

先来看一下很粗暴,但是很直观的效果图:

vue 组件无限嵌套demo

上面的效果图嵌套层级是不是很直观,嘿嘿!!!

想要实现组件的无限嵌套,就要做两个组件,实现原理就是在一个嵌套组件里,引入自己,这样子就可以实现无限的嵌套了。下面就来看看具体的代码吧!

第一个组件:

<template> <div class="tree"> <tree-node v-for="(item, i) in datas" :key="i" :data="item" /> </div> </template> <script> import TreeNode from './TreeNode' export default { data(){ return { datas: [{"id":1,"name":"金字塔","description":"aaaa","pid":"0","path":"0","lock":1,"created_at":"2018-08-30","updated_at":"2018-08-30","childs":[{"id":2,"name":"金字塔1","description":"aaaa","pid":"1","path":"0-2","lock":0,"created_at":"2018-08-30","updated_at":"2018-08-30","childs":[{"id":5,"name":"金字塔1-1","description":"aaaa","pid":"2","path":"0-2-5","lock":0,"created_at":"2018-08-30","updated_at":"2018-08-30","childs":[{"id":8,"name":"金字塔1-1-1","description":"aaaa","pid":"5","path":"0-2-5-8","lock":0,"created_at":"2018-08-30","updated_at":"2018-08-30","childs":[{"id":10,"name":"金字塔1-1-1-1","description":"aaaa","pid":"8","path":"0-2-5-8-10","lock":0,"created_at":"2018-08-30","updated_at":"2018-08-30"}]}]},{"id":11,"name":"金字塔1-2","description":"aaaa","pid":"2","path":"0-2-11","lock":0,"created_at":"2018-08-30","updated_at":"2018-08-30","childs":[{"id":12,"name":"金字塔1-2-1","description":"aaaa","pid":"11","path":"0-2-11-12","lock":0,"created_at":"2018-08-30","updated_at":"2018-08-30"}]}]},{"id":3,"name":"金字塔2","description":"aaaa","pid":"1","path":"0-3","lock":0,"created_at":"2018-08-30","updated_at":"2018-08-30","childs":[{"id":6,"name":"金字塔2-1","description":"aaaa","pid":"3","path":"0-3-6","lock":0,"created_at":"2018-08-30","updated_at":"2018-08-30","childs":[{"id":9,"name":"金字塔2-1-1","description":"aaaa","pid":"6","path":"0-3-6-9","lock":0,"created_at":"2018-08-30","updated_at":"2018-08-30"}]}]}]}] } }, components:{ TreeNode } } </script>

第二个组件:

<template> <div> <p class="title">{{data.name}}</p> <!-- 无限嵌套的重点就是在这里啦-判断是否有子节点,有的话就遍历子节点 --> <template v-if="data.childs"> <tree-node v-for="(item, i) in data.childs" :key="i" :data="item" /> </template> </div> </template> <script> export default { name: 'tree-node', props: ['data'] } </script>

代码很简单,只是大家可能不知道组件还能自己引用自己吧!!!