首页 > 解决方案 > Vuejs 错误:未知的自定义元素是否正确注册了组件

问题描述

我有不同类型的单元格,我想根据输入数据自动获取正确的单元格组件。
所以我创建了一个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.vue, Cell2.vue, Cell3.vue,所以这里没有递归。

// 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');
    }
}

标签: vue.js

解决方案


推荐阅读