方法 1: 使用命名导出
export const useFoo = () => {
return useState('foo', () => 'bar')
}
方法 2: 使用默认导出
// It will be available as useFoo() (camelCase of file name without extension)
export default function () {
return useState('foo', () => 'bar')
}
用法: 您现在可以在 .js、.ts 和 .vue 文件中使用自动导入的可组合项。
<script setup lang="ts">
const foo = useFoo()
</script>
<template>
<div>
{{ foo }}
</div>
</template>
app/composables/ 目录不会为您的代码提供任何额外的响应性功能。相反,可组合项中的任何响应性都是通过 Vue 的 Composition API 机制实现的,例如 ref 和 reactive。请注意,响应式代码也不受限于 app/composables/ 目录的边界。您可以在应用程序中需要的地方自由使用响应性功能。在底层,Nuxt 会自动生成文件 .nuxt/imports.d.ts 来声明类型。
请注意,您必须运行 nuxt prepare、nuxt dev 或 nuxt build,以便 Nuxt 生成类型。
Cannot find name 'useBar'.您可以使用自动导入在一个可组合项中再使用另一个可组合项
export const useFoo = () => {
const nuxtApp = useNuxtApp()
const bar = useBar()
}
您可以从可组合项中访问插件注入
export const useHello = () => {
const nuxtApp = useNuxtApp()
return nuxtApp.$hello
}
Nuxt 只扫描 app/composables/ 目录的顶级文件,例如:
-| composables/
---| index.ts // scanned
---| useFoo.ts // scanned
---| nested/
-----| utils.ts // not scanned
只有 app/composables/index.ts 和 app/composables/useFoo.ts 会被搜索导入。
为了使嵌套模块的自动导入工作,您可以重新导出它们(推荐)或配置扫描器以包含嵌套目录
示例: 从 app/composables/index.ts 文件重新导出您需要的可组合项
// Enables auto import for this export
export { utils } from './nested/utils.ts'
示例: 扫描 app/composables/ 文件夹内的嵌套目录
export default defineNuxtConfig({
imports: {
dirs: [
// Scan top-level composables
'~/composables',
// ... or scan composables nested one level deep with a specific name and file extension
'~/composables/*/index.{ts,js,mjs,mts}',
// ... or scan all composables within given directory
'~/composables/**',
],
},
})