composables

使用 composables/ 目录将你的 Vue composables 自动导入到应用中。

用法

方法 1: 使用命名导出

app/composables/useFoo.ts
export const useFoo = () => {
  return useState('foo', () => 'bar')
}

方法 2: 使用默认导出

app/composables/use-foo.ts or composables/useFoo.ts
// 它将以 useFoo() 可用(文件名去扩展名后的驼峰式)
export default function () {
  return useState('foo', () => 'bar')
}

用法: 现在你可以在 .js.ts.vue 文件中使用自动导入的 composable

app/app.vue
<script setup lang="ts">
const foo = useFoo()
</script>

<template>
  <div>
    {{ foo }}
  </div>
</template>
Nuxt 中的 app/composables/ 目录不会为你的代码提供任何额外的响应式能力。composables 中的任何响应式都是通过 Vue 的组合式 API 机制(例如 ref 和 reactive)来实现的。请注意,响应式代码并不限于 app/composables/ 目录的范围。你可以在应用中任何需要的地方使用响应式特性。
Read more in Docs > 4 X > Guide > Concepts > Auto Imports.
Read and edit a live example in Docs > 4 X > Examples > Features > Auto Imports.

类型

在底层,Nuxt 会自动生成文件 .nuxt/imports.d.ts 来声明类型。

请注意,你需要运行 nuxt preparenuxt devnuxt build 以便让 Nuxt 生成这些类型。

如果你在未启动开发服务器的情况下创建一个 composable,TypeScript 会抛出错误,例如 Cannot find name 'useBar'.

示例

嵌套的 Composables

你可以在一个 composable 中使用另一个 composable(通过自动导入):

app/composables/test.ts
export const useFoo = () => {
  const nuxtApp = useNuxtApp()
  const bar = useBar()
}

访问插件注入

你可以从 composables 中访问 插件注入

app/composables/test.ts
export const useHello = () => {
  const nuxtApp = useNuxtApp()
  return nuxtApp.$hello
}

文件如何被扫描

Nuxt 只扫描位于 app/composables/ 目录 顶层的文件,例如:

Directory Structure
-| composables/
---| index.ts     // 被扫描
---| useFoo.ts    // 被扫描
---| nested/
-----| utils.ts   // 不被扫描

只有 app/composables/index.tsapp/composables/useFoo.ts 会被搜索以用于导入。

要让自动导入在嵌套模块中也能工作,你可以选择重新导出它们(推荐)或配置扫描器以包含嵌套目录:

示例:app/composables/index.ts 文件重新导出你需要的 composables:

app/composables/index.ts
// 为此导出启用自动导入
export { utils } from './nested/utils.ts'

示例:app/composables/ 文件夹内扫描嵌套目录:

nuxt.config.ts
export default defineNuxtConfig({
  imports: {
    dirs: [
      // 扫描顶层 composables
      '~/composables',
      // ... 或者使用特定的名称和文件扩展名扫描嵌套一级的 composables
      '~/composables/*/index.{ts,js,mjs,mts}',
      // ... 或者扫描给定目录内的所有 composables
      '~/composables/**',
    ],
  },
})