onPrehydrate
Use onPrehydrate to run a callback on the client immediately before Nuxt hydrates the page.
此组合式函数在 Nuxt v3.12+ 中可用。
onPrehydrate 是一个组合式生命周期钩子,允许您在客户端 Nuxt 水合页面之前立即运行回调。
这是一个高级工具,应谨慎使用。例如,
nuxt-time 和 @nuxtjs/color-mode 操作 DOM 以避免水合不匹配。用法
在 Vue 组件的 setup 函数中(例如在 <script setup> 中)或在插件中调用 onPrehydrate。它仅在服务器上调用时生效,不会包含在您的客户端构建中。
类型
Signature
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。 - 使用回调和键调用时返回字符串(预水合 id),可用于设置或访问
data-prehydrate-id属性以进行高级用例。
示例
app/app.vue
<script setup lang="ts">
declare const window: Window
// ---cut---
// 在 Nuxt 水合之前运行代码
onPrehydrate(() => {
console.log(window)
})
// 访问根元素
onPrehydrate((el) => {
console.log(el.outerHTML)
// <div data-v-inspector="app.vue:15:3" data-prehydrate-id=":b3qlvSiBeH:"> Hi there </div>
})
// 高级:自己访问/设置 `data-prehydrate-id`
const prehydrateId = onPrehydrate((el) => {})
</script>
<template>
<div>
Hi there
</div>
</template>