useCookie
useCookie 是一个 SSR 友好的可组合函数,用于读取和写入 cookie。
使用方法
在你的页面、组件和插件中,你可以使用 useCookie
以 SSR 友好的方式读取和写入 cookie。
const cookie = useCookie(name, options)
useCookie
仅在 Nuxt 上下文 中有效。返回的 ref 将自动序列化和反序列化 cookie 值为 JSON。
类型
签名
import type { Ref } from 'vue'
import type { CookieParseOptions, CookieSerializeOptions } from 'cookie-es'
export interface CookieOptions<T = any> extends Omit<CookieSerializeOptions & CookieParseOptions, 'decode' | 'encode'> {
decode?(value: string): T
encode?(value: T): string
default?: () => T | Ref<T>
watch?: boolean | 'shallow'
readonly?: boolean
}
export interface CookieRef<T> extends Ref<T> {}
export function useCookie<T = string | null | undefined>(
name: string,
options?: CookieOptions<T>
): CookieRef<T>
参数
name
:cookie 的名称。
options
:控制 cookie 行为的选项。对象可以包含以下属性:
大多数选项将直接传递给 cookie 包。
属性 | 类型 | 默认值 | 描述 |
---|---|---|---|
decode | (value: string) => T | decodeURIComponent + destr | 自定义函数,用于解码 cookie 值。由于 cookie 值具有有限的字符集(且必须是简单字符串),此函数可用于将先前编码的 cookie 值解码为 JavaScript 字符串或其他对象。 注意:如果此函数抛出错误,将返回原始的、未解码的 cookie 值作为 cookie 的值。 |
encode | (value: T) => string | JSON.stringify + encodeURIComponent | 自定义函数,用于编码 cookie 值。由于 cookie 值具有有限的字符集(且必须是简单字符串),此函数可用于将值编码为适合 cookie 值的字符串。 |
default | () => T | Ref<T> | undefined | 当 cookie 不存在时返回默认值的函数。该函数也可以返回一个 Ref 。 |
watch | boolean | 'shallow' | true | 是否监听更改并更新 cookie。true 表示深度监听,'shallow' 表示浅层监听,即仅监听顶级属性的数据更改,false 表示禁用监听。注意:当 cookie 发生更改时,使用 refreshCookie 手动刷新 useCookie 值。 |
readonly | boolean | false | 如果为 true ,则禁用对 cookie 的写入。 |
maxAge | number | undefined | cookie 的最大存活时间(以秒为单位),即 Max-Age Set-Cookie 属性 的值。给定的数字将通过向下取整转换为整数。默认情况下,未设置最大存活时间。 |
expires | Date | undefined | cookie 的到期日期。默认情况下,未设置到期时间。大多数客户端会将此视为“非持久性 cookie”,并在退出浏览器应用程序等条件下删除。 注意:cookie 存储模型规范 规定,如果同时设置了 expires 和 maxAge ,则 maxAge 优先,但并非所有客户端都遵循此规则,因此如果两者都设置,应指向相同的日期和时间!如果 expires 和 maxAge 均未设置,cookie 将仅为会话 cookie,并在用户关闭浏览器时删除。 |
httpOnly | boolean | false | 设置 HttpOnly 属性。 注意:将此设置为 true 时需谨慎,因为符合规范的客户端将不允许客户端 JavaScript 通过 document.cookie 查看 cookie。 |
secure | boolean | false | 设置 Secure Set-Cookie 属性。注意:将此设置为 true 时需谨慎,因为如果浏览器没有 HTTPS 连接,符合规范的客户端将不会在未来将 cookie 发送回服务器。这可能导致水合错误。 |
partitioned | boolean | false | 设置 Partitioned Set-Cookie 属性。注意:此属性尚未完全标准化,未来可能发生变化。 这也意味着许多客户端可能在理解此属性之前会忽略它。 更多信息可在提案中找到。 |
domain | string | undefined | 设置 Domain Set-Cookie 属性。默认情况下,未设置域,大多数客户端只会将 cookie 应用于当前域。 |
path | string | '/' | 设置 Path Set-Cookie 属性。默认情况下,路径被视为“默认路径”。 |
sameSite | boolean | string | undefined | 设置 SameSite Set-Cookie 属性。- true 将 SameSite 属性设置为 Strict ,表示严格的同站执行。- false 不设置 SameSite 属性。- 'lax' 将 SameSite 属性设置为 Lax ,表示宽松的同站执行。- 'none' 将 SameSite 属性设置为 None ,表示明确的跨站 cookie。- 'strict' 将 SameSite 属性设置为 Strict ,表示严格的同站执行。 |
返回值
返回一个表示 cookie 值的 Vue Ref<T>
。更新此 ref 将更新 cookie(除非设置了 readonly
)。该 ref 是 SSR 友好的,可在客户端和服务器端均正常工作。
示例
基本用法
下面的示例创建一个名为 counter
的 cookie。如果 cookie 不存在,它将初始设置为一个随机值。每当我们更新 counter
变量时,cookie 将相应更新。
app.vue
<script setup lang="ts">
const counter = useCookie('counter')
counter.value = counter.value || Math.round(Math.random() * 1000)
</script>
<template>
<div>
<h1>计数器:{{ counter || '-' }}</h1>
<button @click="counter = null">重置</button>
<button @click="counter--">-</button>
<button @click="counter++">+</button>
</div>
</template>
只读 Cookie
<script setup lang="ts">
const user = useCookie(
'userInfo',
{
default: () => ({ score: -1 }),
watch: false
}
)
if (user.value) {
// 实际的 `userInfo` cookie 不会被更新
user.value.score++
}
</script>
<template>
<div>用户分数:{{ user?.score }}</div>
</template>
可写 Cookie
<script setup lang="ts">
const list = useCookie(
'list',
{
default: () => [],
watch: 'shallow'
}
)
function add() {
list.value?.push(Math.round(Math.random() * 1000))
// list cookie 不会因此次更改而更新
}
function save() {
if (list.value) {
// 实际的 `list` cookie 将被更新
list.value = [...list.value]
}
}
</script>
<template>
<div>
<h1>列表</h1>
<pre>{{ list }}</pre>
<button @click="add">添加</button>
<button @click="save">保存</button>
</div>
</template>
API 路由中的 Cookie
你可以使用 h3
包中的 getCookie
和 setCookie
在服务器 API 路由中设置 cookie。
server/api/counter.ts
export default defineEventHandler(event => {
// 读取 counter cookie
let counter = getCookie(event, 'counter') || 0
// 将 counter cookie 增加 1
setCookie(event, 'counter', ++counter)
// 发送 JSON 响应
return { counter }
})
阅读并编辑实时示例中的内容 Docs > Examples > Advanced > Use Cookie.