Context
Nuxt Kit provides a set of utilities to help you work with context. These functions enable you to conveniently access the Nuxt instance from the context without having to pass it as an argument. Nuxt modules allow you to enhance Nuxt’s capabilities. They offer a structured way to keep your code organized and modular.useNuxt
Get the Nuxt instance from the context. It will throw an error if Nuxt is not available.
Type
Return Value
TheuseNuxt function returns the Nuxt instance with the following key properties:
| 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 callback for a specific lifecycle hook. |
callHook | (name: string, ...args: any[]) => Promise<any> | Shortcut for nuxt.hooks.callHook. Triggers a lifecycle hook manually. |
addHooks | (configHooks: NestedHooks) => () => void | Shortcut for nuxt.hooks.addHooks. Registers multiple hooks at once. |
Usage
Example: Setting up transpilation
tryUseNuxt
Get the Nuxt instance from the context. It will return null if Nuxt is not available.
Type
Return Value
ThetryUseNuxt function returns the Nuxt instance if available, or null if Nuxt is not available.
The Nuxt instance has the same properties as described in the useNuxt section.
Usage
Example: Requiring site config
When to use context functions
Note: When you’re working with thesetup 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() and tryUseNuxt() when you’re breaking down your module into smaller components that don’t receive the Nuxt instance as a parameter.