onPrehydrate

源文件
使用 onPrehydrate 在 Nuxt 激活页面之前立即在客户端运行回调函数。
此组合式函数 (composable) 可用于 Nuxt v3.12+ 版本。

onPrehydrate 是一个组合式生命周期钩子,允许你在 Nuxt 激活(hydrate)页面之前立即在客户端运行回调函数。

这是一个高级工具,应谨慎使用。例如:nuxt-time等等@nuxtjs/color-mode操作 DOM 以避免激活不匹配 (hydration mismatches)。

使用

在 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 上下文。
keystring(高级)用于标识预激活脚本的唯一键,对于多根节点等高级场景非常有用。

返回值

  • 当仅通过回调函数调用时,返回 undefined
  • 当同时使用回调和 key 调用时,返回一个字符串(预激活 ID),可用于设置或访问 data-prehydrate-id 属性,以应对高级用例。

示例

app/app.vue
<script setup lang="ts">
declare const window: Window
// ---cut---
// 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>