Vue 警告: 未知的自定义元素: <myCompont> - 是否正确注册了组件?



我是大一新生,当我使用自定义组件时,它会给我这个错误:

Vue 警告: 未知的自定义元素: - 是否正确注册了组件?

组件中使用的ModalBaseNoticeModal.vueproductInfo.vue中使用的NoticeModal组合。

我确定我已经在productInfo.vue中正确导入了NoticeModal,并在NoticeModal.vue中导入了ModalBase.vue,并且全部注册。

但我得到唯一的警告:Unknown custom element: <modal-base>

这是ModalBase.vue

<template>
<div>
<div class="modal-header">
<slot name="header">
<p class="title">This is base</p>
</slot>
</div>
</div>
</template>
<script>
export default {
name: "ModalBase",
data() {
return {show: ''}
}
}
</script>

这是NoticeModal.vue

<template>
<div class="noticeModal">
<modal-base>
<div slot="header">hello</div>
</modal-base>
</div>
</template>
<script>
import {ModalBase} from '@/components/index';

export default {
name: "NoticeModal",
props: ['modalOptions'],
components: {
ModalBase
},
data() {
return {show: ''}
}
}
</script>

这是productInfo.vue

<template>
<div>
<notice-modal></notice-modal>
</div>
</template>
<script>
import {NoticeModal} from '@/components/index';

export default {
name: "productInfo",
components: {
'NoticeModal': NoticeModal
},
data() { }
}
</script>

顺便说一下,这条路径'@/components/index'是正确的,NoticeModalModalBase都已在此文件中正确导入、注册和导出。

@/components/index

import NoticeModal from '@/components/componentsFile/NoticeModal.vue'
import ModalBase from '@/components/componentsFile/ModalBase.vue'

export {
NoticeModal,
ModalBase
}
components: {
'NoticeModal': NoticeModal
},

这些行表示您已注册名为"通知模型"的组件。因此,在您的模板代码中,您应该将此组件与"NoticeModel"一起使用作为 html 标记。

<template>
<div>
<NoticeModel></NoticeModel>
</div>
</template>

您也可以使用以下代码来注册 HTML 样式标记并将其与通知模式一起使用

components: {
'notice-modal': NoticeModal
}

您可能会收到此错误的另一个原因。 您有两个名称相同且扩展名不同的文件

比如:MyComponent.vue 和 MyComponent.js 在同一个文件夹中。

在我的MyComponent中.js我添加了一个名称来解决此错误。 export const componentWorker = {hello: (p1) => {console.log('hello from (JS) ' , p1)},name: "JSCompWorker"}这并不总是发生 - 我还有其他 samename.vue 和 samename.js 一个文件夹,没问题...

您应该直接导入组件。 例如:

而不是

import {ModalBase} from '@/components/index';

import ModalBase from '@/components/ModalBase.vue';

自定义元素可以在 Vue 外部定义,当为 ex 加载外部脚本时。

使用Vue2,您可以在配置中显式使用ignoredElements忽略的元素:https://v2.vuejs.org/v2/api/#ignoredElements

我不知道如何使用 Vue3...

PS:如果你必须在 Vue 中与这种自定义元素进行交互,你可能要等待 Vue 组件挂载并使用 nextTick 来确保合成器可以使用。

最新更新