nuxt logo

文档翻译(非官方)

useCookie

useCookie 是一个支持 SSR 的组合式函数,用于读取和写入 cookies。

用法

在你的页面、组件和插件中,你可以使用 useCookie 以支持 SSR 的方式读取和写入 cookies。

const cookie = useCookie(name, options)

useCookie 仅在 Nuxt 上下文中工作。

返回的 ref 将自动序列化和反序列化 cookie 值为 JSON。

类型

Signature
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) => TdecodeURIComponent + destr自定义函数用于解码 cookie 值。由于 cookie 的值具有有限的字符集(并且必须是简单字符串),此函数可用于将先前编码的 cookie 值解码为 JavaScript 字符串或其他对象。
注意: 如果此函数抛出错误,原始的、未解码的 cookie 值将作为 cookie 的值返回。
encode(value: T) => stringJSON.stringify + encodeURIComponent自定义函数用于编码 cookie 值。由于 cookie 的值具有有限的字符集(并且必须是简单字符串),此函数可用于将值编码为适合 cookie 值的字符串。
default() => T | Ref<T>undefined如果 cookie 不存在,返回默认值的函数。该函数也可以返回一个 Ref
watchboolean | 'shallow'true是否监视更改并更新 cookie。true 表示深度监视,'shallow' 表示浅层监视,即仅监视顶级属性的数据更改,false 表示禁用。
注意: 当 cookie 更改时,手动刷新 useCookie 值,使用 refreshCookie
readonlybooleanfalse如果为 true,则禁用对 cookie 的写入。
maxAgenumberundefinedcookie 的最大存活时间(以秒为单位),即 Max-Age Set-Cookie 属性 的值。给定的数字将通过向下取整转换为整数。默认情况下,没有设置最大存活时间。
expiresDateundefinedcookie 的过期日期。默认情况下,没有设置过期时间。大多数客户端会将其视为“非持久性 cookie”,并在退出 Web 浏览器应用程序等条件下删除它。
注意: cookie 存储模型规范指出,如果同时设置了 expiresmaxAge,则 maxAge 优先,但并非所有客户端都会遵循这一点,因此如果同时设置了两者,它们应指向相同的日期和时间!
如果 expiresmaxAge 都未设置,cookie 将仅限于会话,并在用户关闭浏览器时删除。
httpOnlybooleanfalse设置 HttpOnly 属性。
注意: 将此设置为 true 时要小心,因为合规的客户端将不允许客户端 JavaScript 在 document.cookie 中查看 cookie。
securebooleanfalse设置 Secure Set-Cookie 属性
注意: 将此设置为 true 时要小心,因为合规的客户端如果浏览器没有 HTTPS 连接,将不会在未来将 cookie 发送回服务器。这可能导致 hydration 错误。
partitionedbooleanfalse设置 Partitioned Set-Cookie 属性
注意: 这是一个尚未完全标准化的属性,未来可能会发生变化。
这也意味着许多客户端可能会忽略此属性,直到它们理解它。
更多信息可以在 提案 中找到。
domainstringundefined设置 Domain Set-Cookie 属性。默认情况下,没有设置域,大多数客户端会认为仅将 cookie 应用于当前域。
pathstring'/'设置 Path Set-Cookie 属性。默认情况下,路径被视为 "默认路径"
sameSiteboolean | stringundefined设置 SameSite Set-Cookie 属性
- trueSameSite 属性设置为 Strict,以严格的同站点策略进行强制。
- false 不设置 SameSite 属性。
- 'lax'SameSite 属性设置为 Lax,以宽松的同站点策略进行强制。
- 'none'SameSite 属性设置为 None,以明确的跨站点 cookie。
- 'strict'SameSite 属性设置为 Strict,以严格的同站点策略进行强制。

返回值

返回一个 Vue Ref<T>,表示 cookie 的值。更新 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: {{ 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) {
  // 实际的 `userInfo` cookie 不会被更新
  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 不会因这个更改而更新
}

function save() {
  if (list.value) {
    // 实际的 `list` cookie 将被更新
    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 包中的 getCookiesetCookie 在服务器 API 路由中设置 cookies。

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 }
})
示例代码的编辑与预览examples > advanced > use-cookie