Vue递归组件

我心飞翔 分类:vue

Vue递归组件

1、递归组件

  组件可以在自己的模板种递归调用自身,但这需要使用name选项为组件指定一个内部调用的名称。当调用Vue.createApp({}).component({})全局注册组件时,这个全局的ID会自动设置为该组件的name选项。
  递归组件和程序语言中的递归函数调用一样,都需要有一个条件结束递归,否则就会导致无限循环。例如,可以通过v-if指令(表达式计算为假时)结束递归。

2、实例

  下面看一个分类树状显示的例子,代码如下:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
	</head>
	<body>
		<div id="app">
			<category-component :list="categories"></category-component>
		</div>
		
	    <script src="https://unpkg.com/vue@next"></script>
        <script>
            const CategoryComponent = {
          		name: 'catComp',
          		props: {
          			list: {
          				type: Array
          			}
          		},
          		template: `
          			<ul>
          				<!-- 如果list为空,表示没有子分类了,结束递归 -->
          				<template v-if="list">
        						<li v-for="cat in list">
        							{{cat.name}}
        							<catComp :list="cat.children"/>
        						</li>
        					</template>
          			</ul>
          			`
            }
        	const app = Vue.createApp({
        	    data(){
        	        return {
        	            categories: [
        	  		    {
        		  			name: '程序设计', 
        		  			children: [
        		  				{
        		  					name: 'Java', 
        		  					children: [
        		  						{name: 'Java SE'}, 
        		  						{name: 'Java EE'}
        		  					]
        		  				}, 
        		  				{
        		  					name: 'C++'
        		  				}
        		  			]
        	  		    },
        			    {
          					name: '前端框架', 
          					children: [
          						{name: 'Vue.js'}, 
          						{name: 'React'}
          					]
        			    }]
        	        }
        	  	},
        	    components: {
        	  	    CategoryComponent
        	    }
        	}).mount('#app');
        </script>
	</body>
</html>

  渲染结果:

Vue递归组件

想想递归函数这个就很好理解了

回复

我来回复
  • 暂无回复内容