【求助】vue组件递归调用异常问题
本文由 小茗同学 发表于 2020-04-09 浏览(245)
最后修改 2020-04-09 标签:vue

问题描述

组件A里面引用组件B,组件B同时又引用组件A,就这么简单,但是总是报如下错误:

[Vue warn]: Failed to mount component: template or render function not defined

最小复现代码

index.vue:

<style>
.test-node {
	border: solid 1px #aaa;
	margin: 8px;
	padding: 8px;
}
</style>
<template>
	<div>
		<h1>测试Vue组件递归循环调用:</h1>
		<nodes :nodes="nodes"/>
	</div>
</template>
<script>
	import Nodes from './nodes';
	export default {
		components: {
			Nodes,
		},
		data() {
			return {
				nodes: [
					{name: 'function', id: 1},
					{name: 'hsf', id: 2},
					{name: 'loop', id: 3, children: [
						{name: 'child1', id: 4},
						{name: 'child2', id: 5},
					]},
					{name: 'test', id: 6},
				]
			}
		}
	}
</script>

nodes.vue:

<template>
	<div>
		<template v-for="node in nodes">
			<node :node="node" :key="node.id"/>
		</template>
	</div>
</template>
<script>
	import Node from './node';
	export default {
		components: {
			Node,
		},
		name: 'nodes',
		props: {
			nodes: Array
		},
	}
</script>

node.vue:

<template>
	<div class="test-node">
		{{node.name}}
		<nodes v-if="node.children" :nodes="node.children"/>
	</div>
</template>
<script>
	import Nodes from './nodes';
	export default {
		components: {
			Nodes,
		},
		props: {
			node: Object
		},
	}
</script>

结果

期望效果:

实际效果:

并且控制台报错:

已知没问题的写法

丢弃node.vue,把node.vue的代码copy到nodes.vue里面就没问题:

修改后的nodes.vue:

<template>
	<div>
		<template v-for="node in nodes">
			<!-- <node :node="node" :key="node.id"/> -->
			<div class="test-node" :key="node.id">
				{{node.name}}
				<nodes v-if="node.children" :nodes="node.children"/>
			</div>
		</template>
	</div>
</template>
<script>
	import Node from './node';
	export default {
		components: {
			Node,
		},
		name: 'nodes',
		props: {
			nodes: Array
		},
	}
</script>

待解决

至于为什么分开写会报错,找了1天了还没找到原因,如果有知道的欢迎评论指出!跪谢!