Composables 目录
Nuxt 3使用
composables/
目录使用
auto-imports
自动将Vue组合导入到应用中!
在底层,Nuxt自动生成文件
.nuxt/imports.d.ts
来声明类型。
注意,为了让Nuxt生成类型,你必须运行
nuxi prepare
,
nuxi dev
或
nuxi build
。如果你在没有运行开发服务器的情况下创建了一个可组合对象,TypeScript会抛出一个错误,比如
Cannot find name 'useBar'.
Usage
Method 1: Using named export
export const useFoo = () => { return useState('foo', () => 'bar')}
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
文件中使用自动导入组合
<template> <div> {{ foo }} </div></template><script setup>const foo = useFoo()</script>
示例
Nested Composables
你可以在使用自动导入的另一个可组合对象中使用一个可组合对象:
export const useFoo = () => { const nuxtApp = useNuxtApp() const bar = useBar()}
访问插件注入
你可以从可组合文件中访问 plugin injections
export const useHello = () => { const nuxtApp = useNuxtApp() return nuxtApp.$hello}
如何扫描文件
Nuxt只扫描
composables/
目录的顶层文件,例如:
composables | - index.ts // scanned | - useFoo.ts // scanned | - nested | --- utils.ts // not scanned
只有
composables/index.ts
和
composables/useFoo.ts
会被搜索导入。
为了让自动导入工作于嵌套模块,你可以重新导出它们(推荐)或配置扫描器包含嵌套目录:
示例:
从
composables/index.ts
中重新导出您需要的组合的文件:
// Enables auto import for this exportexport { utils } from './nested/utils.ts'
示例:
扫描
composables/
文件夹内的嵌套目录:
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/**' ] }})