onPrehydrate
使用 onPrehydrate 在 Nuxt 頁面水合 (hydrate) 之前立即在客戶端運行回調。
這個組合式函式在 Nuxt v3.12+ 版本中可用。
onPrehydrate
是一個組合式生命週期鉤子,允許您在 Nuxt 頁面水合之前立即在客戶端運行回調。
這是一個進階工具,應謹慎使用。例如,
nuxt-time
和 @nuxtjs/color-mode
操作 DOM 以避免水合不匹配。用法
onPrehydrate
可以直接在 Vue 元件的 setup 函數中調用(例如,在 <script setup>
中),或在插件中調用。它只會在伺服器端調用時生效,並且不會包含在您的客戶端建置中。
參數
callback
:一個將被字串化並內聯到 HTML 中的函數。它不應有任何外部依賴(例如自動導入)或引用在回調之外定義的變數。回調將在 Nuxt 運行時初始化之前執行,因此它不應依賴於 Nuxt 或 Vue 的上下文。
範例
app.vue
<script setup lang="ts">
// 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>