生命周期钩子
Nuxt Hooks(构建时)
¥Nuxt Hooks (Build Time)
这些钩子可用于 Nuxt 模块 和构建上下文。
¥These hooks are available for Nuxt Modules and build context.
nuxt.config.ts
中 在
¥Within nuxt.config.ts
export default defineNuxtConfig({
hooks: {
close: () => { }
}
})
在 Nuxt 模块中
¥Within Nuxt Modules
import { defineNuxtModule } from '@nuxt/kit'
export default defineNuxtModule({
setup (options, nuxt) {
nuxt.hook('close', async () => { })
}
})
:
探索所有可用的 Nuxt hooks。
¥Explore all available Nuxt hooks.
::
应用钩子(运行时)
¥App Hooks (Runtime)
应用钩子主要用于 Nuxt 插件 钩住渲染生命周期,但也可用于 Vue 可组合组件。
¥App hooks can be mainly used by Nuxt Plugins to hook into rendering lifecycle but could also be used in Vue composables.
export default defineNuxtPlugin((nuxtApp) => {
nuxtApp.hook('page:start', () => {
/* your code goes here */
})
})
:
探索所有可用的 App hooks。
¥Explore all available App hooks.
::
服务器钩子(运行时)
¥Server Hooks (Runtime)
这些钩子可用于 服务器插件 连接到 Nitro 的运行时行为。
¥These hooks are available for server plugins to hook into Nitro's runtime behavior.
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 生命周期钩子的信息。
¥Learn more about available Nitro lifecycle hooks.
::
其他 Hooks
¥Additional Hooks
你可以通过扩充 Nuxt 提供的类型来添加其他钩子。这对于模块很有用。
¥You can add additional hooks by augmenting the types provided by Nuxt. This can be useful for modules.
import { HookResult } from "@nuxt/schema";
declare module '#app' {
interface RuntimeNuxtHooks {
'your-nuxt-runtime-hook': () => HookResult
}
interface NuxtHooks {
'your-nuxt-hook': () => HookResult
}
}
declare module 'nitro/types' {
interface NitroRuntimeHooks {
'your-nitro-hook': () => void;
}
}