Nuxt4 自动导入机制
在 Vue 中,组件和工具函数都要手动 import,Nuxt 的自动导入机制改变了这一点,app/components/、app/composables/、app/utils/ 目录下的文件会被自动导入,即写即用。
组件自动导入
在 app/components/ 下创建任何 Vue 组件,都可以在整个应用中直接使用,无需 import:
app/components/
├── Navbar.vue
├── PostCard.vue
└── UserAvatar.vue
<!-- app/pages/index.vue -->
<template>
<div>
<!-- 直接用,不用 import -->
<Navbar />
<PostCard v-for="post in posts" :key="post.id" :post="post" />
</div>
</template>
app/components/Navbar.vue 创建完成即可用,改文件内容,所有用到它的页面同步热更新。
组件目录嵌套
组件可以放在子目录里组织,Nuxt 会把目录名作为组件名的一部分:
app/components/
└── base/
└── Button.vue → 组件名 BaseButton
<template>
<BaseButton>确定</BaseButton>
</template>
规则是目录前缀按驼峰式拼到文件名前,子目录再嵌套同理,如 components/base/form/Input.vue 的组件名是 BaseFormInput。
如果不想让子目录参与组件名,可以把目录名加下划线后缀,如 _base/,目录内的文件不会带前缀。
组合式函数自动导入
app/composables/ 目录下的组合式函数同样自动导入:
// app/composables/useCounter.ts
export function useCounter() {
const count = ref(0)
const increment = () => count.value++
return { count, increment }
}
<!-- app/pages/counter.vue -->
<script setup>
// 直接调用,不用 import
const { count, increment } = useCounter()
</script>
<template>
<div>
<p>计数:{{ count }}</p>
<button @click="increment">加一</button>
</div>
</template>
composables 文件中的导出必须是函数,Nuxt 只对导出的函数做自动导入,普通变量(如常量)不会自动导入,需要放到 app/utils/。
工具函数自动导入
app/utils/ 目录存放不依赖组件上下文的普通函数:
// app/utils/format.ts
export function formatPrice(price) {
return `¥${price.toFixed(2)}`
}
export const SITE_NAME = '我的网站'
<script setup>
const price = formatPrice(19.9) // 直接使用
</script>
<template>
<p>{{ price }}</p>
</template>
utils/ 里的导出可以是函数,也可以是变量,都会自动导入。
背后的机制
自动导入看起来像魔法,其实原理不复杂,构建时 Nuxt 会扫描 components/、composables/、utils/ 等目录,生成一份「导入映射」,记录每个文件对应的导入路径,当你在某个地方用到一个组件或函数,Nuxt 就自动补上对应的 import,没用到的部分根本不会被引入。
显式导入
自动导入偶尔会出问题,比如组件名和其他来源冲突,这时可以显式导入,使用 ~ 别名指向项目根目录:
<script setup>
import Navbar from '~/components/Navbar.vue'
</script>
~ 和 @ 都指向项目根目录,~/components/... 可以正常解析路径。
自动导入速查表
| 目录 | 导入方式 | 说明 |
|---|---|---|
app/components/ |
标签直接用 | 组件名包含目录前缀 |
app/composables/ |
函数直接调用 | 只导入导出的函数 |
app/utils/ |
直接使用 | 函数和变量均可 |
| 其他目录 | 手动 import | 用 ~/ 或 @/ 开头写路径 |
一句话总结:组件放 components/,函数放 composables/ 或 utils/,从此不用写 import。