递归组件
关键是组件在模板内能调用自身,关键是name属性
首先我们先定义数据格式
list: [ { title: '标题1' }, { title: '标题2', children: [ { title: '标题2-子标题1' }, { title: '标题2-子标题2' } ] }, { title: '标题3', children: [ { title: '标题3-子标题1', children: [ { title: '标题3-子标题1-子标题1' }, { title: '标题3-子标题1-子标题2' } ] } ] } ]
首先我们父组件代码
<div v-for='v in list' :key='v.title'> <div>{{v.title}}</div> <v-menu v-if='v.children' :data='v.children'></v-menu> </div>
子组件代码
使用name来调用自身实现递归
<template> <div> <div v-for='(v, idx) in data' :key='idx'> <div>{{v.title}}</div> <menu-item v-show='v.children' :data='v.children'></menu-item> </div> </div> </template> <script> export default { name: 'menu-item', props: { data: { type: Array, default: () => [] } } } </script>