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>