useHydration
useHydration
的设计参考了 ensure state synchronization and restoration during SSR。如果你需要在 Nuxt 中创建支持服务器端渲染 (SSR) 的全局响应式状态,推荐使用 useState
。useHydration
是一个内置的可组合函数,它提供了一种在每次发出新的 HTTP 请求时在服务器端设置数据并在客户端接收该数据的方法。这样,useHydration
允许你完全控制 hydration 循环。
¥useHydration
is a built-in composable that provides a way to set data on the server side every time a new HTTP request is made and receive that data on the client side. This way useHydration
allows you to take full control of the hydration cycle.
服务器上 get
函数返回的数据存储在 nuxtApp.payload
中,并使用 useHydration
第一个参数提供的唯一键。在 hydration 过程中,这些数据会在客户端检索,从而避免冗余计算或 API 调用。
¥The data returned from the get
function on the server is stored in nuxtApp.payload
under the unique key provided as the first parameter to useHydration
. During hydration, this data is then retrieved on the client, preventing redundant computations or API calls.
用法
¥Usage
export default defineNuxtPlugin((nuxtApp) => {
const myStore = new MyStore()
if (import.meta.server) {
nuxt.hooks.hook('app:rendered', () => {
nuxtApp.payload.myStoreState = myStore.getState()
})
}
if (import.meta.client) {
nuxt.hooks.hook('app:created', () => {
myStore.setState(nuxtApp.payload.myStoreState)
})
}
})
export default defineNuxtPlugin((nuxtApp) => {
const myStore = new MyStore()
useHydration(
'myStoreState',
() => myStore.getState(),
(data) => myStore.setState(data)
)
})
类型
¥Type
useHydration <T> (key: string, get: () => T, set: (value: T) => void) => void
参数
¥Parameters
key
:一个唯一键,用于标识 Nuxt 应用中的数据。get
:仅在服务器端执行的函数(在 SSR 渲染完成时调用)用于设置初始值。set
:仅在客户端执行的函数(在创建初始 Vue 实例时调用)用于接收数据。