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 值使用的字符串。 |
默认 | () => T | Ref<T> | 未定义 | 如果 cookie 不存在,则返回默认值的函数。该函数还可以返回一个 Ref 。 |
watch | boolean | 'shallow' | true | 是否监听更改并更新 cookie。true 表示深度监听,'shallow' 表示浅层监听,即只监听顶层属性的数据更改,false 表示禁用。注意:当 cookie 发生更改时,使用 refreshCookie 手动刷新 useCookie 值。 |
readonly | boolean | false | 如果为 true ,则禁用写入 cookie。 |
maxAge | number | 未定义 | cookie 的最大年龄(秒),即 Set-Cookie 属性中的 Max-Age 值。给定数字将通过四舍五入转换为整数。默认情况下,不设置最大年龄。。给定数字将通过向下取整转换为整数。默认情况下,不设置最大年龄。 |
expires | Date | 未定义 | cookie 的过期日期。默认情况下,不设置过期日期。大多数客户端会将其视为“非持久性 cookie”,并在退出 Web 浏览器应用程序等条件下删除它。 注意: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>
只读 Cookies
<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>
可写 Cookies
<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>
API 路由中的 Cookies
你可以使用来自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 }
})
在 Docs > 4 X > Examples > Advanced > Use Cookie 中阅读和编辑实时示例。