[英]Vuejs: Dynamic Recursive components (Tree Like Structure)
我正在嘗試制作一個調用自身“列表”版本的自定義組件。 我不斷收到錯誤
未知的自定義元素: - 您是否正確注冊了組件? 對於遞歸組件,請確保提供“名稱”選項。
我已經包含了一個名稱選項,如下所示,但這並不能解決問題。
知道它可能是什么嗎?
TestCompList.vue
<-- List 組件
<template>
<div>
<p>I am a list</p>
<template v-for="block in blocks">
<test-comp :name="block.name" :header="block.name" :more="block.more" :key="block.id"></test-comp>
</template>
</div>
</template>
<script>
import TestComp from './TestComp';
export default {
name: "TestCompList",
components: {
TestComp
},
props: ['blocks'],
}
</script>
TestComp.vue
<--- 單一組件
<template>
<div>
<h3>{{header}}</h3>
<p>{{name}}</p>
<div class="mr-5" v-if="more">
<test-comp-list :blocks="more"></test-comp-list>
</div>
</div>
</template>
<script>
import TestCompList from './TestCompList';
export default {
name: "TestComp",
props: ['header', 'name', 'more'],
components: {
TestCompList
}
}
</script>
Page.vue
<-- 傳遞數據的頁面
<template>
<div>
<h3>Testing Recursive components</h3>
<test-comp-list :blocks="blocks"></test-comp-list>
</div>
</template>
<script>
import TestCompList from "./TestCompList";
export default {
components: {
TestCompList
},
data() {
return {
blocks: [
{
id: 1,
name: "test1",
header: "test1Header"
},
{
id: 2,
name: "test2",
header: "test2Header"
},
{
id: 3,
name: "test3",
header: "test3Header",
more: [
{
id: 4,
name: "test4",
header: "test4Header"
},
{
id: 5,
name: "test5",
header: "test5Header",
more: [
{
id: 6,
name: "test6",
header: "test6Header"
},
{
id: 7,
name: "test7",
header: "test7Header"
}
]
}
]
}
]
};
}
};
</script>
有任何想法嗎? 我在這里解決了類似的問題-> Vuejs: Dynamic Recursive components
但似乎無法在這里應用解決方案。 最糟糕的部分是有時它似乎工作,有時它不
幫助! 我可能會錯過什么?
你有一個循環依賴。 查看遞歸文檔正下方的文檔: 組件之間的循環引用。 您需要添加一個beforeCreate
掛鈎以在加載時引入子依賴項。
這並不是您想象的那種遞歸問題,因為如果它是遞歸的,組件就會嘗試調用自身。 相反,它試圖聲明對組件的依賴關系,而該組件又依賴於試圖聲明依賴關系的組件; 因此是“圓形”。
實際上, vue-loader
不知道該做什么,因為您的依賴關系圖如下所示:
Page -> TestCompList -> TestComp -> TestCompList -> TestComp -> ...
正如文檔所說,如果您在全局范圍內注冊這些組件,這將不是問題(但是您將擁有不必要的廣泛依賴結構)。 在不全局注冊的情況下解決此問題的方法是讓其中一個組件在運行時在beforeCreate
掛鈎中聲明其依賴項要求。
TestCompList.vue
<template>
<div>
<p>I am a list</p>
<template v-for="block in blocks">
<TestComp :name="block.name" :header="block.name" :more="block.more" :key="block.id"></TestComp>
</template>
</div>
</template>
<script>
export default {
name: "TestCompList",
props: ['blocks'],
beforeCreate: function(){
this.$options.components.TestComp = require("./TestComp.vue").default;
}
}
</script>
更易讀的方法是使用Webpack 的異步導入
您需要做的就是將TestCompList.vue
的 components 部分更改為:
components: {
TestComp: () => import('./TestComp.vue'),
}
您的組件名稱與您使用的標簽不匹配
name: "TestComp",
<test-comp>
應該:
name: "test-comp",
<test-comp>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.