useCookie

useCookie 是一个服务器端渲染 (SSR) 友好的可组合项,用于读取和写入 Cookie。

在你的页面、组件和插件中,你可以使用 useCookie(一个支持服务器端渲染 (SSR) 的组合)来读取和写入 Cookie。

¥Within your pages, components and plugins you can use useCookie, an SSR-friendly composable to read and write cookies.

const cookie = useCookie(name, options)
useCookie 仅在 Nuxt context 模块中工作。
useCookie ref 会自动将 cookie 值序列化并反序列化为 JSON。

示例

¥Example

以下示例创建了一个名为 counter 的 cookie。如果 Cookie 不存在,则初始设置为一个随机值。每当我们更新 counter 变量时,cookie 都会相应更新。

¥The example below creates a cookie called counter. If the cookie doesn't exist, it is initially set to a random value. Whenever we update the counter variable, the cookie will be updated accordingly.

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>
Read and edit a live example in Docs > Examples > Advanced > Use Cookie.
当 Cookie 使用 refreshCookie 更改时,手动刷新 useCookie 值。

选项

¥Options

Cookie 可组合项接受多个选项,可让你修改 Cookie 的行为。

¥Cookie composable accepts several options which let you modify the behavior of cookies.

大多数选项将直接传递给 cookie 包。

¥Most of the options will be directly passed to the cookie package.

maxAge / expires

使用这些选项设置 Cookie 的有效期。

¥Use these options to set the expiration of the cookie.

maxAge:指定 number(以秒为单位)作为 Max-Age Set-Cookie 属性 的值。给定的数字将通过向下舍入转换为整数。默认情况下,未设置最大使用期限。

¥maxAge: Specifies the number (in seconds) to be the value for the Max-Age Set-Cookie attribute. The given number will be converted to an integer by rounding down. By default, no maximum age is set.

expires:指定 Date 对象作为 Expires Set-Cookie 属性 的值。默认情况下,未设置过期时间。大多数客户端会将其视为 "非持久性 Cookie",并在退出 Web 浏览器应用等情况下将其删除。

¥expires: Specifies the Date object to be the value for the Expires Set-Cookie attribute. By default, no expiration is set. Most clients will consider this a "non-persistent cookie" and will delete it on a condition like exiting a web browser application.

cookie storage model specification 规定,如果同时设置了 expiresmaxAge,则 maxAge 优先,但并非所有客户端都遵循此规定,因此如果同时设置了两者,则它们应该指向相同的日期和时间!
如果 expiresmaxAge 均未设置,则 cookie 将仅用于会话,并在用户关闭浏览器时被删除。

httpOnly

指定 HttpOnly Set-Cookie 属性boolean 值。当值为真时,HttpOnly 属性会被设置;否则不是。默认情况下,HttpOnly 属性未设置。

¥Specifies the boolean value for the HttpOnly Set-Cookie attribute. When truthy, the HttpOnly attribute is set; otherwise it is not. By default, the HttpOnly attribute is not set.

将此设置为 true 时要小心,因为兼容的客户端将不允许客户端 JavaScript 查看 document.cookie 中的 cookie。¥Be careful when setting this to true, as compliant clients will not allow client-side JavaScript to see the cookie in document.cookie.

secure

指定 Secure Set-Cookie 属性boolean 值。当值为真时,Secure 属性会被设置;否则不是。默认情况下,Secure 属性未设置。

¥Specifies the boolean value for the Secure Set-Cookie attribute. When truthy, the Secure attribute is set; otherwise it is not. By default, the Secure attribute is not set.

将其设置为 true 时要小心,因为如果浏览器没有 HTTPS 连接,兼容的客户端将来不会将 cookie 发送回服务器。这可能会导致混合错误。¥Be careful when setting this to true, as compliant clients will not send the cookie back to the server in the future if the browser does not have an HTTPS connection. This can lead to hydration errors.

partitioned

指定 Partitioned Set-Cookie 属性的 boolean 值。当值为真时,Partitioned 属性会被设置,否则不设置。默认情况下,Partitioned 属性未设置。

¥Specifies the boolean value for the Partitioned Set-Cookie attribute. When truthy, the Partitioned attribute is set, otherwise it is not. By default, the Partitioned attribute is not set.

这是一个尚未完全标准化的属性,将来可能会发生变化。这也意味着许多客户端可能会忽略此属性,直到他们理解它为止。更多信息可以在 proposal 中找到。

domain

指定 Domain Set-Cookie 属性 的值。默认情况下,未设置域名,大多数客户端会考虑仅将 Cookie 应用于当前域名。

¥Specifies the value for the Domain Set-Cookie attribute. By default, no domain is set, and most clients will consider applying the cookie only to the current domain.

path

指定 Path Set-Cookie 属性 的值。默认情况下,该路径被视为 "默认路径"

¥Specifies the value for the Path Set-Cookie attribute. By default, the path is considered the "default path".

sameSite

指定 SameSite Set-Cookie 属性booleanstring 值。

¥Specifies the boolean or string value for the SameSite Set-Cookie attribute.

  • true 会将 SameSite 属性设置为 Strict,以支持严格的同站 Cookie 执行。
  • false 不会设置 SameSite 属性。
  • 'lax' 会将 SameSite 属性设置为 Lax,以支持宽松的同站 Cookie 执行。
  • 'none' 会将 SameSite 属性设置为 None,以显式指定跨站 Cookie。
  • 'strict' 会将 SameSite 属性设置为 Strict,以支持严格的同站 Cookie 执行。

有关不同执行级别的更多信息,请参阅 规范

¥More information about the different enforcement levels can be found in the specification.

encode

指定用于编码 Cookie 值的函数。由于 Cookie 值的字符集有限(并且必须是简单字符串),因此可以使用此函数将值编码为适合 Cookie 值的字符串。

¥Specifies a function that will be used to encode a cookie's value. Since the value of a cookie has a limited character set (and must be a simple string), this function can be used to encode a value into a string suited for a cookie's value.

默认编码器为 JSON.stringify + encodeURIComponent

¥The default encoder is the JSON.stringify + encodeURIComponent.

decode

指定用于解码 Cookie 值的函数。由于 Cookie 的值具有有限的字符集(并且必须是简单字符串),因此此函数可用于将先前编码的 Cookie 值解码为 JavaScript 字符串或其他对象。

¥Specifies a function that will be used to decode a cookie's value. Since the value of a cookie has a limited character set (and must be a simple string), this function can be used to decode a previously encoded cookie value into a JavaScript string or other object.

默认解码器为 decodeURIComponent + destr

¥The default decoder is decodeURIComponent + destr.

如果此函数抛出错误,则原始的、未解码的 cookie 值将作为 cookie 的值返回。

default

指定返回 Cookie 默认值的函数。该函数也可以返回一个 Ref

¥Specifies a function that returns the cookie's default value. The function can also return a Ref.

readonly

允许访问 Cookie 值,但无法设置它。

¥Allows accessing a cookie value without the ability to set it.

watch

指定 watch Cookie 引用数据的 booleanstring 值。

¥Specifies the boolean or string value for watch cookie ref data.

  • true - 将监视 Cookie 引用数据的变化及其嵌套属性(默认)。
  • shallow - 将仅监视顶层属性的 Cookie 引用数据的变化
  • false - 不会监视 Cookie 引用数据的变化。
当 Cookie 使用 refreshCookie 更改时,手动刷新 useCookie 值。

示例 1:

¥Example 1:

<script setup lang="ts">
const user = useCookie(
  'userInfo',
  {
    default: () => ({ score: -1 }),
    watch: false
  }
)

if (user.value && user.value !== null) {
  user.value.score++; // userInfo cookie not update with this change
}
</script>

<template>
  <div>User score: {{ user?.score }}</div>
</template>

示例 2:

¥Example 2:

<script setup lang="ts">
const list = useCookie(
  'list',
  {
    default: () => [],
    watch: 'shallow'
  }
)

function add() {
  list.value?.push(Math.round(Math.random() * 1000))
  // list cookie not update with this change
}

function save() {
  if (list.value && list.value !== null) {
    list.value = [...list.value]
    // list cookie update with this change
  }
}
</script>

<template>
  <div>
    <h1>List</h1>
    <pre>{{ list }}</pre>
    <button @click="add">Add</button>
    <button @click="save">Save</button>
  </div>
</template>

¥Cookies in API Routes

你可以使用 h3 包中的 getCookiesetCookie 在服务器 API 路由中设置 Cookie。

¥You can use getCookie and setCookie from h3 package to set cookies in server API routes.

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 }
})
Read and edit a live example in Docs > Examples > Advanced > Use Cookie.