ライフサイクルフック

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 フックを探索します。

アプリフック (ランタイム)

アプリフックは、主に 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)
  })
})
利用可能な Nitro ライフサイクルフックの詳細を確認してください。

カスタムフックの追加

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
  }
}