You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
51 lines
1.2 KiB
51 lines
1.2 KiB
// SSR 上下文与 cookie 管理(与业务无关的通用模块)
|
|
|
|
export interface SSRContext {
|
|
cache?: Map<string, any>
|
|
cookies?: Record<string, string>
|
|
piniaState?: object
|
|
setCookies?: string[]
|
|
[key: string]: any
|
|
}
|
|
|
|
export function createSSRContext(): SSRContext {
|
|
return {
|
|
cache: new Map(),
|
|
piniaState: {},
|
|
cookies: {},
|
|
setCookies: []
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 将 SSR 上下文注入到 window 对象
|
|
* 在客户端水合时调用
|
|
*/
|
|
export function hydrateSSRContext(context: SSRContext): void {
|
|
if (typeof window !== 'undefined') {
|
|
if (context.cache && Array.isArray(context.cache)) {
|
|
context.cache = new Map(context.cache)
|
|
}
|
|
;(window as any).__SSR_CONTEXT__ = context
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 清除 SSR 上下文
|
|
* 在客户端水合完成后调用
|
|
*/
|
|
export function clearSSRContext(): void {
|
|
if (typeof window !== 'undefined') {
|
|
delete (window as any).__SSR_CONTEXT__
|
|
}
|
|
}
|
|
|
|
// 通用获取 SSR 上下文(客户端从 window,服务端从 app 实例)
|
|
export function resolveSSRContext(instance?: any): SSRContext | null {
|
|
if (typeof window !== 'undefined') {
|
|
return (window as any).__SSR_CONTEXT__ || null
|
|
}
|
|
return instance?.appContext?.config?.globalProperties?.$ssrContext || null
|
|
}
|
|
|
|
|
|
|