mirror of
https://github.com/nuxt/nuxt.git
synced 2025-01-18 17:35:57 +00:00
feat(useCookie): support default value (#2147)
This commit is contained in:
parent
f3082ca601
commit
010febd1b3
@ -7,9 +7,11 @@ import destr from 'destr'
|
|||||||
import { useNuxtApp } from '#app'
|
import { useNuxtApp } from '#app'
|
||||||
|
|
||||||
type _CookieOptions = Omit<CookieSerializeOptions & CookieParseOptions, 'decode' | 'encode'>
|
type _CookieOptions = Omit<CookieSerializeOptions & CookieParseOptions, 'decode' | 'encode'>
|
||||||
|
|
||||||
export interface CookieOptions<T=any> extends _CookieOptions {
|
export interface CookieOptions<T=any> extends _CookieOptions {
|
||||||
decode?(value: string): T
|
decode?(value: string): T
|
||||||
encode?(value: T): string;
|
encode?(value: T): string;
|
||||||
|
default?: () => T
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface CookieRef<T> extends Ref<T> {}
|
export interface CookieRef<T> extends Ref<T> {}
|
||||||
@ -23,10 +25,10 @@ export function useCookie <T=string> (name: string, _opts?: CookieOptions<T>): C
|
|||||||
const opts = { ...CookieDefaults, ..._opts }
|
const opts = { ...CookieDefaults, ..._opts }
|
||||||
const cookies = readRawCookies(opts)
|
const cookies = readRawCookies(opts)
|
||||||
|
|
||||||
const cookie = ref(cookies[name])
|
const cookie = ref(cookies[name] ?? _opts.default?.())
|
||||||
|
|
||||||
if (process.client) {
|
if (process.client) {
|
||||||
watch(cookie, () => { writeClientCookie(name, cookie.value, opts) })
|
watch(cookie, () => { writeClientCookie(name, cookie.value, opts as CookieSerializeOptions) })
|
||||||
} else if (process.server) {
|
} else if (process.server) {
|
||||||
const initialValue = cookie.value
|
const initialValue = cookie.value
|
||||||
const nuxtApp = useNuxtApp()
|
const nuxtApp = useNuxtApp()
|
||||||
@ -38,7 +40,7 @@ export function useCookie <T=string> (name: string, _opts?: CookieOptions<T>): C
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
return cookie
|
return cookie as CookieRef<T>
|
||||||
}
|
}
|
||||||
|
|
||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
@ -70,7 +72,7 @@ function writeClientCookie (name: string, value: any, opts: CookieSerializeOptio
|
|||||||
|
|
||||||
function writeServerCookie (res: ServerResponse, name: string, value: any, opts: CookieSerializeOptions = {}) {
|
function writeServerCookie (res: ServerResponse, name: string, value: any, opts: CookieSerializeOptions = {}) {
|
||||||
if (res) {
|
if (res) {
|
||||||
// TODO: Try to smart join with exisiting Set-Cookie headers
|
// TODO: Try to smart join with existing Set-Cookie headers
|
||||||
appendHeader(res, 'Set-Cookie', serializeCookie(name, value, opts))
|
appendHeader(res, 'Set-Cookie', serializeCookie(name, value, opts))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user