生命週期鉤子
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
}
}