Vuejs 错误:未知的自定义元素您是否正确注册了组件

时间:2021-01-19 10:26:52

标签: vue.js

我有不同类型的单元格,我想根据输入数据自动获取正确的单元格组件。
所以我创建了一个 Cell.vue 组件,它执行此操作

// Cell.vue
<template>
    <div>
        <component :is="cellComponent" v-bind="cellProps"></component>
    </div>
<template>

<script>
import Cell1 from '...'
import Cell2 from '...'
import Cell3 from '...'
import SpecialCell from '...'

export default {
    name: 'Cell',
    props: ['data'],
    ...
    // get cell component and props depending on data
    computed: {
        cellComponent() {
            switch(this.data.key) {
                case 'cell1':
                    return Cell1;
                ...
                case 'specialCell':
                    return SpecialCell;
            }
        }

    }
}
</script

到目前为止,这有效。现在,SpecialCell.vue 导入了 Cell.vue,但需要注意的是,只有 Cell1.vueCell2.vueCell3.vue 被调用,所以这里没有递归。< /p>

// SpecialCell.vue
<template>
    <div>
        ...
        <table-cell></table-cell>
        ...
    </div>
<template>

<script>
import Cell from '...'

export default {
    name: 'SpecialCell'
    props: [....],
    components: {
        'table-cell': Cell
    }
    ...
}
</script

仍然发生以下错误 Unknown custom element: <table-cell> - did you register the component correctly? For recursive components, make sure to provide the "name" option. 并且未呈现 table-cell 组件。所以我为每个单元格类型添加了一个名称属性,但没有成功。

奇怪的是,当我重新加载页面时,我只会收到这个错误。当我更改函数名称并让 vue 重新加载页面(npm run serve)时,table-cell 组件会正确呈现。

如果我复制 Cell.vue 并在 SpecialCell.vue 中引用这个复制的组件,一切正常。当然我可以创建一个mixin或扩展单元组件,以避免代码重复,但我想了解问题,也许可以在不创建另一个文件的情况下解决问题。

有人知道解决办法吗?

编辑:问题在于 import SpecialCell from '...' 中的这一行 Cell.vue。当我在 cellComponent() 中使用延迟加载时,没有错误

cellComponent() {
    switch(this.data.key) {
        case 'cell1':
            return Cell1;
        ...
        case 'specialCell':
            return () => import('.../SpecialCell');
    }
}

0 个答案:

没有答案