composables
用法
¥Usage
方法 1:使用命名导出
¥Method 1: Using named export
export const useFoo = () => {
return useState('foo', () => 'bar')
}
方法 2:使用默认导出
¥Method 2: Using default export
// It will be available as useFoo() (camelCase of file name without extension)
export default function () {
return useState('foo', () => 'bar')
}
用法:你现在可以在 .js
、.ts
和 .vue
文件中使用自动导入的可组合函数。
¥Usage: You can now use auto imported composable in .js
, .ts
and .vue
files
<script setup lang="ts">
const foo = useFoo()
</script>
<template>
<div>
{{ foo }}
</div>
</template>
composables/
目录不为你的代码提供任何额外的响应式功能。相反,可组合项中的任何响应式都是使用 Vue 的 Composition API 机制(例如 ref 和 react)实现的。请注意,响应式代码也不限于 composables/
目录的边界。你可以在应用中任何需要的地方自由使用响应式特性。类型
¥Types
Nuxt 内部会自动生成文件 .nuxt/imports.d.ts
来声明类型。
¥Under the hood, Nuxt auto generates the file .nuxt/imports.d.ts
to declare the types.
请注意,你必须运行 nuxi prepare
、nuxi dev
或 nuxi build
才能让 Nuxt 生成类型。
¥Be aware that you have to run nuxi prepare
, nuxi dev
or nuxi build
in order to let Nuxt generate the types.
Cannot find name 'useBar'.
。示例
¥Examples
嵌套可组合项
¥Nested Composables
你可以使用自动导入将一个可组合项在另一个可组合项中使用:
¥You can use a composable within another composable using auto imports:
export const useFoo = () => {
const nuxtApp = useNuxtApp()
const bar = useBar()
}
访问插件注入
¥Access plugin injections
你可以从可组合项中访问 插件注入:
¥You can access plugin injections from composables:
export const useHello = () => {
const nuxtApp = useNuxtApp()
return nuxtApp.$hello
}
如何扫描文件
¥How Files Are Scanned
Nuxt 仅扫描 composables/
目录 顶层的文件,例如:
¥Nuxt only scans files at the top level of the composables/
directory, e.g.:
-| composables/
---| index.ts // scanned
---| useFoo.ts // scanned
---| nested/
-----| utils.ts // not scanned
只有 composables/index.ts
和 composables/useFoo.ts
会被搜索导入。
¥Only composables/index.ts
and composables/useFoo.ts
would be searched for imports.
要使嵌套模块的自动导入功能正常工作,你可以重新导出它们(推荐)或配置扫描器以包含嵌套目录:
¥To get auto imports working for nested modules, you could either re-export them (recommended) or configure the scanner to include nested directories:
示例:从 composables/index.ts
文件中重新导出你需要的可组合项:
¥Example: Re-export the composables you need from the composables/index.ts
file:
// Enables auto import for this export
export { utils } from './nested/utils.ts'
示例:扫描 composables/
文件夹中的嵌套目录:
¥Example: Scan nested directories inside the composables/
folder:
export default defineNuxtConfig({
imports: {
dirs: [
// Scan top-level modules
'composables',
// ... or scan modules nested one level deep with a specific name and file extension
'composables/*/index.{ts,js,mjs,mts}',
// ... or scan all modules within given directory
'composables/**'
]
}
})