[英]How to import two VueJS components inside eachother?
我有兩個組件,一個item
組件和一個folder
組件。 每個item
都包含它自己的folder
組件,每個folder
組件都包含一個item
列表。
所以我試圖在folder
組件中使用item
組件,反之亦然,但是,我收到錯誤: unknown custom element: <item> - did you register the component correctly? For recursive components, make sure to provide the "name" option.
unknown custom element: <item> - did you register the component correctly? For recursive components, make sure to provide the "name" option.
盡管我在兩個組件上都設置了name
選項。 有任何想法嗎?
代碼如下
item.vue
<template>
<div class="item" style="height: 30px">
. . .
<folder v-if="item.hasChildren" :id="id"></folder>
</div>
</template>
<script scoped>
import Folder from './folder.vue';
export default {
name: 'item',
props: ['id'],
components: {
Folder
}
};
</script>
folder.vue
<template>
<div class="folder">
<template v-for="(child, index) in children">
<item :last-item="index === children.length - 1" :key="child.id" :id="child.id"></item>
</template>
</div>
</template>
<script>
import Item from "./item.vue";
export default {
name: 'folder',
props: ['id', 'hasChildren'],
components: {
Item
}
};
</script>
這可能是由於組件之間的循環引用而發生的..
當你仔細觀察時,你會發現這些組件實際上是渲染樹中彼此的后代和祖先——一個悖論!
要解決這個悖論,您可以使用Vue.component
全局注冊組件,也可以將其中一個組件的導入推遲到以后(通過將導入移動到beforeCreate
掛鈎或使用此處演示的異步組件)..
folder.vue
<template>
<div class="folder">
<template v-for="(child, index) in children">
<item :last-item="index === children.length - 1" :key="child.id" :id="child.id"></item>
</template>
</div>
</template>
<script>
export default {
name: 'folder',
props: ['id', 'hasChildren'],
components: {
'item': () => import('./item.vue')
}
};
</script>
您需要像這樣在組件對象中提供鍵(名稱),
項目.vue
components: {
folder: Folder
}
文件夾.vue
components: {
item: Item
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.