簡體   English   中英

如何在彼此內部導入兩個 VueJS 組件?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM