在我的 nuxt 应用程序中,嵌套目录中的组件不会按预期自动导入。对于我的一些组件,我有类似以下内容:
vue 2.6.12
,nuxt 2.15.0
components\
目录结构
TopArea\
--SomeComponent.vue
<template>
<header class="header">
<div>Hello</div>
<SomeComponent />
</header>
</template>
应用程序中没有其他组件具有名称
SomeComponent
。在上面的示例中,我收到错误:Unknown custom element: <SomeComponent> - did you register the component correctly? For recursive components, make sure to provide the "name" option.
。我可以通过在组件文件名之前指定目录名称 (TopAreaSomeComponent
)、使用 nuxt.config 中的前缀选项或手动导入组件来解决此问题。这很令人困惑,因为 docs 状态:
嵌套目录
如果嵌套目录中有组件,例如:
components/baseButton.vue
组件名称将基于其自己的文件名。因此,该组件将是:
<button />
它接着说“为了清楚起见,我们建议您在文件名中使用目录名称”。但这似乎是一条规则,而不是建议。如果我不使用目录名作为文件名的一部分,则动态导入不适用于嵌套目录中的组件。
这是文档中的错误还是我读错了?
自 Nuxt 2.15.0 起,
components
的工作方式发生了变化,如本 github 问题中所述。
根据您的结构以及您希望如何处理组织,您可以根据此处提供的迁移指南相应地编辑您的配置:https://github.com/nuxt/components#v1-to-v2
或者您也可以简单地设置
pathPrefix
选项,让所有组件都可用,而无需任何前缀。
nuxt.config.js/ts
components: [
{
path: '~/components', // will get any components nested in let's say /components/test too
pathPrefix: false,
},
]
PS:该解决方案也适用于 Nuxt3。
该文档实际上确实需要更新:https://nuxtjs.org/docs/2.x/directory-struct/components#components-discovery
这就是它的工作原理:对于给定页面
<template>
<div>
<yolo-swag /> <!-- no need for <nested-yolo-swag /> here -->
</div>
</template>
并使用以下文件树
看起来像这是新的官方语法
import { defineNuxtConfig } from 'nuxt'
export default defineNuxtConfig({
components: {
global: true,
dirs: ['~/components']
},
})
这可能已经有了答案。但为了向这里的人说明解决方案,这里是根据文档的方式:
<TopAreaSomeComponent />
如果你的组件嵌套很深:
components / TopArea / SomeComponent.vue
https://nuxtjs.org/docs/directory-struct/components/#nested-directories