这篇文章主要介绍vue中递归组件的实现方法有哪些,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!
js里面有递归算法,同时,我们也可以利用props来实现vue模板的递归调用,但是前提是组件拥有 name 属性
父组件:slotDemo.vue:
<template>
<p>
<!-----递归组件----->
<ul>
<simple3 :tree="item" v-for="item in tree"></simple3>
</ul>
</p>
</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
<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字段来区分是哪一级的菜单然后对其不同的样式进行处理
最后的效果:
以上是“vue中递归组件的实现方法有哪些”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。