onPrehydrate
使用 onPrehydrate 在 Nuxt hydrate 页面之前立即在客户端运行回调。
此可组合项在 Nuxt v3.12+ 版本中可用。
onPrehydrate
是一个可组合函数的生命周期钩子,它允许你在 Nuxt 数据合并页面之前立即在客户端运行回调。
¥onPrehydrate
is a composable lifecycle hook that allows you to run a callback on the client immediately before
Nuxt hydrates the page.
这是一个高级实用程序,应谨慎使用。例如,
nuxt-time
和 @nuxtjs/color-mode
会操作 DOM 以避免水合不匹配。用法
¥Usage
onPrehydrate
可以在 Vue 组件的 setup 函数中直接调用(例如,在 <script setup>
中),也可以在插件中调用。它仅在服务器上调用时才会生效,并且不会包含在客户端构建中。
¥onPrehydrate
can be called directly in the setup function of a Vue component (for example, in <script setup>
), or in a plugin.
It will only have an effect when it is called on the server, and it will not be included in your client build.
参数
¥Parameters
callback
:一个函数,用于在 HTML 中字符串化和内联。它不应该有任何外部依赖(例如自动导入)或引用在回调之外定义的变量。回调将在 Nuxt 运行时初始化之前运行,因此它不应依赖于 Nuxt 或 Vue 上下文。
示例
¥Example
app.vue
// onPrehydrate is guaranteed to run before Nuxt hydrates
onPrehydrate(() => {
console.log(window)
})
// As long as it only has one root node, you can access the element
onPrehydrate((el) => {
console.log(el.outerHTML)
// <div data-v-inspector="app.vue:15:3" data-prehydrate-id=":b3qlvSiBeH:"> Hi there </div>
})
// For _very_ advanced use cases (such as not having a single root node) you
// can access/set `data-prehydrate-id` yourself
const prehydrateId = onPrehydrate((el) => {})
</script>
<template>
<div>
Hi there
</div>
</template>