onPrehydrate

源文件
使用 onPrehydrate 在 Nuxt 激活页面之前,立即在客户端运行回调。
此可组合函数在 Nuxt v3.12+ 中可用。

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

返回值

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

示例

app/app.vue
// 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>