mirror of
https://github.com/nuxt/nuxt.git
synced 2024-11-30 01:17:16 +00:00
dc47c64f14
Co-authored-by: Daniel Roe <daniel@roe.dev> Co-authored-by: Sébastien Chopin <seb@nuxtjs.com> Co-authored-by: Pooya Parsa <pooya@pi0.io> Co-authored-by: pooya parsa <pyapar@gmail.com> Co-authored-by: Clément Ollivier <clement.o2p@gmail.com>
76 lines
1.9 KiB
Markdown
76 lines
1.9 KiB
Markdown
---
|
|
title: "Lifecycle Hooks"
|
|
description: "Nuxt provides a powerful hooking system to expand almost every aspect using hooks."
|
|
---
|
|
|
|
# Lifecycle Hooks
|
|
|
|
Nuxt provides a powerful hooking system to expand almost every aspect using hooks. This feature is powered by [unjs/hookable](https://github.com/unjs/hookable).
|
|
|
|
## Nuxt Hooks (Build Time)
|
|
|
|
These hooks are available for [Nuxt Modules](/guide/going-further/modules) and build context.
|
|
|
|
### Usage with `nuxt.config`
|
|
|
|
```js [nuxt.config]
|
|
export default defineNuxtConfig({
|
|
hooks: {
|
|
'close': () => { }
|
|
}
|
|
})
|
|
```
|
|
|
|
### Usage with Nuxt Modules
|
|
|
|
```js
|
|
import { defineNuxtModule } from '@nuxt/kit'
|
|
|
|
export default defineNuxtModule({
|
|
setup (options, nuxt) {
|
|
nuxt.hook('close', async () => { })
|
|
})
|
|
})
|
|
```
|
|
|
|
## App Hooks (Runtime)
|
|
|
|
App hooks can be mainly used by [Nuxt Plugins](/guide/directory-structure/plugins) to hook into rendering lifecycle but could also be used in Vue composables.
|
|
|
|
### Usage with Plugins
|
|
|
|
```js [plugins/test.ts]
|
|
export default defineNuxtPlugin((nuxtApp) => {
|
|
nuxtApp.hook('page:start', () => {
|
|
/* your code goes here */
|
|
})
|
|
})
|
|
```
|
|
|
|
::alert{icon=👉}
|
|
Learn more about [available lifecycle hooks](/api/advanced/hooks)
|
|
::
|
|
|
|
## Nitro App Hooks (Runtime)
|
|
|
|
These hooks are available for [Nitro plugins](https://nitro.unjs.io/guide/advanced/plugins) to hook into Nitro's runtime behavior.
|
|
|
|
### Usage within a Nitro Plugin
|
|
|
|
```js [~/server/plugins/test.ts]
|
|
export default defineNitroPlugin((nitroApp) => {
|
|
nitroApp.hooks.hook('render:html', (html, { event }) => {
|
|
console.log('render:html', html)
|
|
html.bodyAppend.push('<hr>Appended by custom plugin')
|
|
})
|
|
|
|
nitroApp.hooks.hook('render:response', (response, { event }) => {
|
|
console.log('render:response', response)
|
|
})
|
|
})
|
|
```
|
|
|
|
::alert{icon=👉}
|
|
Learn more about available [Nitro lifecycle hooks](/api/advanced/hooks#nitro-hooks-runtime-server-side).
|
|
::
|