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
refresh?: 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 值的字符串。 |
默认 | () => T | Ref<T> | 未定义 | 当 cookie 不存在时返回默认值的函数。该函数还可以返回一个 Ref。 |
watch | boolean | 'shallow' | true | 是否监听更改并更新 cookie。true 表示深度监听,'shallow' 表示浅层监听(即仅针对顶级属性的数据更改),false 表示禁用。注意:当使用 refreshCookie 更改了 cookie 时,请手动刷新 useCookie 值。 |
refresh v4.4 | boolean | false | 如果为 true,则在每次显式写入时(例如 cookie.value = cookie.value),即使值本身没有改变,cookie 的过期时间也会被刷新。注意:过期时间不会自动刷新——你必须赋值给 .value 来触发它。 |
readonly | boolean | false | 如果为 true,则禁止写入 cookie。 |
maxAge | number | 未定义 | cookie 的最大生存时间(以秒为单位),即 Max-Age Set-Cookie 属性。给定的数字将通过向下取整转换为整数。默认情况下,不设置最大生存时间。 |
expires | Date | 未定义 | cookie 的过期日期。默认情况下,不设置过期时间。大多数客户端会将其视为“非持久性 cookie”,并会在退出网页浏览器应用程序等条件下将其删除。 注意:cookie 存储模型规范指出,如果同时设置了 expires 和 maxAge,则 maxAge 具有优先权,但并非所有客户端都一定会遵守这一点,因此如果同时设置了两者,它们应该指向相同的日期和时间!如果既未设置 expires 也未设置 maxAge,则该 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 | 未定义 | 设置 Domain Set-Cookie 属性。默认情况下,不设置域,大多数客户端会认为该 cookie 仅适用于当前域。 |
path | string | '/' | 设置 Path Set-Cookie 属性。默认情况下,该路径被视为 “默认路径”。 |
sameSite | boolean | string | 未定义 | 设置 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/app.vue
<script setup lang="ts">
const counter = useCookie('counter')
counter.value ||= Math.round(Math.random() * 1000)
</script>
<template>
<div>
<h1>Counter: {{ counter || '-' }}</h1>
<button @click="counter = null">
reset
</button>
<button @click="counter--">
-
</button>
<button @click="counter++">
+
</button>
</div>
</template>
只读 Cookie
app/app.vue
<script setup lang="ts">
const user = useCookie(
'userInfo',
{
default: () => ({ score: -1 }),
watch: false,
},
)
if (user.value) {
// the actual `userInfo` cookie will not be updated
user.value.score++
}
</script>
<template>
<div>User score: {{ user?.score }}</div>
</template>
可写 Cookie
app/app.vue
<script setup lang="ts">
const list = useCookie(
'list',
{
default: () => [],
watch: 'shallow',
},
)
function add () {
list.value?.push(Math.round(Math.random() * 1000))
// list cookie won't be updated with this change
}
function save () {
// the actual `list` cookie will be updated
list.value &&= [...list.value]
}
</script>
<template>
<div>
<h1>List</h1>
<pre>{{ list }}</pre>
<button @click="add">
Add
</button>
<button @click="save">
Save
</button>
</div>
</template>
刷新 Cookie
app/app.vue
<script setup lang="ts">
const session = useCookie(
'session', {
maxAge: 60 * 60, // 1 hour
refresh: true,
default: () => 'active',
})
// Even if the value does not change,
// the cookie expiration will be refreshed
// every time the setter is called
session.value = 'active'
</script>
<template>
<div>Session: {{ session }}</div>
</template>
API 路由中的 Cookie
你可以使用来自 h3 包的 getCookie 和 setCookie 在服务器 API 路由中设置 cookie。
server/api/counter.ts
export default defineEventHandler((event) => {
// Read counter cookie
let counter = getCookie(event, 'counter') || 0
// Increase counter cookie by 1
setCookie(event, 'counter', ++counter)
// Send JSON response
return { counter }
})
在 文档 > 4.x > 示例 > 高级 > Use Cookie 中阅读并编辑在线示例。