onPrehydrate 是一个可组合的生命周期钩子,允许你在 Nuxt 注水页面之前,立即在客户端运行回调。
nuxt-time等等@nuxtjs/color-mode操作 DOM 以避免注水不匹配。在 Vue 组件的 setup 函数中(例如,在 <script setup> 中)或在插件中调用 onPrehydrate。它仅在服务器上调用时才有效,并且不会包含在你的客户端构建中。
export function onPrehydrate (callback: (el: HTMLElement) => void): void
export function onPrehydrate (callback: string | ((el: HTMLElement) => void), key?: string): undefined | string
| 参数 | 类型 | 必需 | 描述 |
|---|---|---|---|
callback | ((el: HTMLElement) => void) | string | 是 | 一个函数(或字符串化函数),用于在 Nuxt 注水之前运行。它将被字符串化并内联到 HTML 中。不应有外部依赖项或引用回调外部的变量。在 Nuxt 运行时初始化之前运行,因此不应依赖 Nuxt 或 Vue 上下文。 |
key | string | 否 | (高级) 用于标识预注水脚本的唯一键,适用于多个根节点等高级场景。 |
undefined。data-prehydrate-id 属性,以用于高级用例。// Run code before Nuxt hydrates
onPrehydrate(() => {
console.log(window)
})
// Access the root element
onPrehydrate((el) => {
console.log(el.outerHTML)
// <div data-v-inspector="app.vue:15:3" data-prehydrate-id=":b3qlvSiBeH:"> Hi there </div>
})
// Advanced: access/set `data-prehydrate-id` yourself
const prehydrateId = onPrehydrate((el) => {})
</script>
<template>
<div>
Hi there
</div>
</template>