相关说明

官方文档:组件之间的循环引用

本人的运行版本为 vue-cli@2.5.1,启用项目后,将以下 js 文件和 vue 文件放置在相应的目录中运行。

main.js

1
2
3
4
5
6
7
8
import Vue from 'vue'
import App from './App'

new Vue({
el: '#app',
template: '<App/>',
components: { App }
})

main.js 导入 App 组件,并在 components 中注册 App 组件。

App.vue

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
<template>
<div id="app">
<li v-for="folder in folders">
<tree-folder v-bind:folder="folder"></tree-folder>
</li>
</div>
</template>

<script>
import TreeFolder from './components/tree-folder'
export default {
data: function () {
return {
folders: [
{
name: 'folder1',
children: [{
name: 'folder1 - folder1',
children: [{
name: 'folder1 - folder1 - folder1'
}]
}, {
name: 'folder1 - folder2',
children: [{
name: 'folder1 - folder2 - folder1'
}, {
name: 'folder1 - folder2 - folder2'
}]
}]
},
{
name: 'folder 2',
children: [{
name: 'folder2 - folder1',
children: [{
name: 'folder2 - folder1 - folder1'
}]
}, {
name: 'folder2 - folder2',
children: [{
name: 'folder2-content1'
}]
}]
},
{
name: 'folder 3',
children: [{
name: 'folder3 - folder1',
children: [{
name: 'folder3 - folder1 - folder1'
}]
}, {
name: 'folder3 - folder2',
children: [{
name: 'folder3-content1'
}]
}]
}
]
}
},
components: {
TreeFolder
}
}
</script>

App 组件导入 TreeFolder 组件,并在 components 中注册 TreeFolder 组件。

components/tree-folder.vue

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<template>
<p>
<span>{{ folder.name }}</span>
<tree-folder-contents :children="folder.children"></tree-folder-contents>
</p>
</template>

<script>
// 官方文档:「在我们的例子中,将 tree-folder 组件做为切入起点。我们知道制造矛盾的是 tree-folder-contents 子组件,所以我们在 tree-folder 组件的生命周期钩子函数 beforeCreate 中去注册 tree-folder-contents 组件」

// 所以原先通过 import 导入组件,然后在 components 中注册组件的方式,改为了在 beforeCreate 函数中去注册组件

// import TreeFolderContents from './tree-folder-contents'
export default {
props: ['folder'],
data: function () {
return {}
},
components: {
// TreeFolderContents
},
beforeCreate: function () {
this.$options.components.TreeFolderContents = require('./tree-folder-contents')
}
}
</script>

TreeFolder 组件导入 TreeFolderContents 组件,并在 components 中注册 TreeFolderContents 组件。

components/tree-folder-contents.vue

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<template>
<ul>
<li v-for="child in children">
<tree-folder v-if="child.children" :folder="child"></tree-folder>
<span v-else>{{ child.name }}</span>
</li>
</ul>
</template>

<script>
import TreeFolder from './tree-folder'

export default {
props: ['children'],
components: {
TreeFolder
}
}
</script>

TreeFolderContents 组件又导入 TreeFolder 组件,并在 components 中注册 TreeFolder 组件,产生了循环引用。