下面vue.js教程栏目通过实例制作一个三级菜单,来介绍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字段来区分是哪一级的菜单然后对其不同的样式进行处理
最后的效果:

相关推荐:2020年前端vue面试题大汇总(附答案)vue教程推荐:2020最新的5个vue.js视频教程精选
更多编程相关知识,请访问:编程教学!!
以上就是vue中递归组件的实现方法介绍(附实例:三级菜单)的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号