Контекст
Nuxt modules allow you to enhance Nuxt's capabilities. They offer a structured way to keep your code organized and modular. If you're looking to break down your module into smaller components, Nuxt offers the useNuxt and tryUseNuxt functions. These functions enable you to conveniently access the Nuxt instance from the context without having to pass it as an argument.
setup function in Nuxt modules, Nuxt is already provided as the second argument. This means you can access it directly without needing to call useNuxt().useNuxt
Получите экземпляр Nuxt из контекста. Он выбросит ошибку, если Nuxt недоступен.
Usage
import { useNuxt } from '@nuxt/kit'
const setupSomeFeature = () => {
const nuxt = useNuxt()
// You can now use the nuxt instance
console.log(nuxt.options)
}
Type
// @errors: 2391
import type { Nuxt } from '@nuxt/schema'
// ---cut---
function useNuxt(): Nuxt
Return Value
The useNuxt function returns the Nuxt instance, which contains all the options and methods available in Nuxt.
| Property | Type | Description |
|---|---|---|
options | NuxtOptions | The resolved Nuxt configuration. |
hooks | Hookable<NuxtHooks> | The Nuxt hook system. Allows registering and listening to lifecycle events. |
hook | (name: string, (...args: any[]) => Promise<void> | void) => () => void | Shortcut for nuxt.hooks.hook. Registers a single callback for a specific lifecycle hook. |
callHook | (name: string, ...args: any[]) => Promise<any> | Shortcut for nuxt.hooks.callHook. Triggers a lifecycle hook manually and runs all registered callbacks. |
addHooks | (configHooks: NestedHooks) => () => void | Shortcut for nuxt.hooks.addHooks. Registers multiple hooks at once. |
Примеры
import { useNuxt } from '@nuxt/kit'
export const setupTranspilation = () => {
const nuxt = useNuxt()
if (nuxt.options.builder === '@nuxt/webpack-builder') {
nuxt.options.build.transpile ||= []
nuxt.options.build.transpile.push('xstate')
}
}
// @module: esnext
// @filename: setupTranspilation.ts
export const setupTranspilation = () => {}
// @filename: module.ts
import { defineNuxtModule } from '@nuxt/kit'
// ---cut---
import { setupTranspilation } from './setupTranspilation'
export default defineNuxtModule({
setup () {
setupTranspilation()
},
})
tryUseNuxt
Получите экземпляр Nuxt из контекста. Он вернет null, если Nuxt недоступен.
Usage
import { tryUseNuxt } from '@nuxt/kit'
function setupSomething () {
const nuxt = tryUseNuxt()
if (nuxt) {
// You can now use the nuxt instance
console.log(nuxt.options)
} else {
console.log('Nuxt is not available')
}
}
Тип
// @errors: 2391
import type { Nuxt } from '@nuxt/schema'
// ---cut---
function tryUseNuxt(): Nuxt | null
Return Value
The tryUseNuxt function returns the Nuxt instance if available, or null if Nuxt is not available.
The Nuxt instance as described in the useNuxt section.
Примеры
declare module '@nuxt/schema' {
interface NuxtOptions {
siteConfig: SiteConfig
}
}
// ---cut---
import { tryUseNuxt } from '@nuxt/kit'
interface SiteConfig {
title?: string
}
export const requireSiteConfig = (): SiteConfig => {
const nuxt = tryUseNuxt()
if (!nuxt) {
return {}
}
return nuxt.options.siteConfig
}
// @module: esnext
// @filename: requireSiteConfig.ts
interface SiteConfig {
title?: string
}
export const requireSiteConfig = (): SiteConfig => {
return {}
}
// @filename: module.ts
// ---cut---
import { defineNuxtModule, useNuxt } from '@nuxt/kit'
import { requireSiteConfig } from './requireSiteConfig'
export default defineNuxtModule({
setup (_, nuxt) {
const config = requireSiteConfig()
nuxt.options.app.head.title = config.title
},
})
Компоненты
Nuxt Kit предоставляет набор утилит, которые помогут вам работать с компонентами. Вы можете зарегистрировать компоненты глобально или локально, а также добавить директории для сканирования на наличие компонентов.
Страницы
Nuxt Kit предоставляет набор утилит, которые помогут вам создавать и использовать страницы. Вы можете использовать эти утилиты для манипулирования конфигурацией страниц или для определения правил маршрутизации.