onPrehydrate
使用 onPrehydrate 在 Nuxt 对页面进行 hydration 之前的客户端立即运行回调。
该组合式函数在 Nuxt v3.12+ 中可用。 :
onPrehydrate 是一个组合式生命周期钩子,允许你在 Nuxt 对页面进行 hydration 之前的客户端立即运行回调。
这是一个高级工具,应当谨慎使用。例如,nuxt-time 和 @nuxtjs/color-mode 会操作 DOM 以避免 hydration 不匹配。
:
用法
在 Vue 组件的 setup 函数(例如在 <script setup> 中)或插件中调用 onPrehydrate。该调用本身只在服务端生效,并从你的客户端构建中移除。然而,你传入的回调会被序列化并内联到 HTML 中,因此它会在 Nuxt hydration 之前在浏览器中运行。这意味着它可以访问 window 和 DOM 等浏览器全局对象。
类型
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 hydration 之前运行的函数(或字符串化函数)。它会被字符串化并内联到 HTML 中。不应有外部依赖或引用回调之外的变量。在 Nuxt 运行时初始化之前运行,因此不应依赖 Nuxt 或 Vue 上下文。 |
key | string | 否 | (高级)用于标识预 hydration 脚本的唯一 key,对多个根节点等高级场景很有用。 |
返回值
- 仅传入 callback 函数时返回
undefined。 - 传入 callback 和 key 时返回一个字符串(预 hydration id),可用于为高级用例设置或访问
data-prehydrate-id属性。
示例
app/app.vue
<script setup lang="ts">
declare const window: Window
// ---cut---
onPrehydrate(() => {
// 在浏览器中运行,就在 Nuxt hydration 之前
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>
在底层,回调会在构建时被字符串化并压缩,然后作为 <script> 标签内联到服务端渲染的 HTML 中,就在闭合的 </body> 标签之前。对于上面的示例,渲染的 HTML 包含类似这样的内容:
<div data-prehydrate-id=":b3qlvSiBeH:"> Hi there </div>
<script>(()=>{console.log(window)})()</script>
<script>document.querySelectorAll('[data-prehydrate-id*=":b3qlvSiBeH:"]').forEach(el=>{console.log(el.outerHTML)})</script>
当回调接受 el 参数时,组件的根元素会被打上 data-prehydrate-id 属性,以便内联脚本能够找到它。