ライフサイクルフック
Nuxt は、フックを使用してほぼすべての側面を拡張するための強力なフッキングシステムを提供します。
フッキングシステムは、unjs/hookable.
Nuxt フック (ビルドタイム)
これらのフックは、Nuxt モジュール とビルドコンテキストで利用できます。
nuxt.config.ts 内
nuxt.config.ts
export default defineNuxtConfig({
hooks: {
close: () => { },
},
})
Nuxt モジュール内
import { defineNuxtModule } from '@nuxt/kit'
export default defineNuxtModule({
setup (options, nuxt) {
nuxt.hook('close', async () => { })
},
})
アプリフック (ランタイム)
アプリフックは、主に Nuxt プラグイン でレンダリングライフサイクルにフックするために使用できますが、Vue コンポーザブルでも使用できます。
app/plugins/test.ts
export default defineNuxtPlugin((nuxtApp) => {
nuxtApp.hook('page:start', () => {
/* your code goes here */
})
})
サーバーフック (ランタイム)
これらのフックは、サーバープラグイン で Nitro のランタイム動作にフックするために利用できます。
~/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)
})
})
カスタムフックの追加
Nuxt のフックインターフェースを拡張することで、独自のカスタムフックサポートを定義できます。
import type { HookResult } from '@nuxt/schema'
declare module '#app' {
interface RuntimeNuxtHooks {
'your-nuxt-runtime-hook': () => HookResult
}
interface NuxtHooks {
'your-nuxt-hook': () => HookResult
}
}
declare module 'nitropack/types' {
interface NitroRuntimeHooks {
'your-nitro-hook': () => void
}
}