Home >Web Front-end >Vue.js >Introduction to the implementation method of recursive components in Vue (with examples: three-level menu)
The following Vue.js tutorial column uses examples to create a three-level menu to introduce the implementation method of recursive components in Vue. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.
#There is a recursive algorithm in js. At the same time, we can also use props to implement recursive calls to vue templates, but the premise is that the component has the name attribute
Parent component: 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>
Child component: 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>
The above is a child component with the name defined as simple03. Then call itself in the template, combined with v-for to implement recursion
In order to prevent an infinite loop, v-if is added as a judgment condition when calling itself
When calling in the parent component, you need to pass in a tree through props;
In order to distinguish each level of menu, I added a test field to each sub-collection in the tree to distinguish Which level of menu then processes its different styles
The final effect:
##Related recommendations:For more programming-related knowledge, please visit:
2020 Summary of front-end vue interview questions (with answers)
vue tutorial recommendation: 2020 latest 5 vue.js video tutorial selections
Programming Teaching! !
The above is the detailed content of Introduction to the implementation method of recursive components in Vue (with examples: three-level menu). For more information, please follow other related articles on the PHP Chinese website!