透過 100 多個技巧的集合來學習 Nuxt!

useCookie

useCookie 是一個 SSR 友善的可組合式函式,用於讀取和寫入 cookies。

在您的頁面、元件和外掛程式中,您可以使用 useCookie,這是一個 SSR 友善的可組合式函式,用於讀取和寫入 cookies。

const cookie = useCookie(name, options)
useCookie 僅在 Nuxt 上下文 中運作。
useCookie ref 將自動序列化和反序列化 cookie 值為 JSON。

範例

以下範例建立一個名為 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>
文件 > 範例 > 進階 > 使用 Cookie中閱讀和編輯即時範例。
當 cookie 變更時,使用 refreshCookie 手動重新整理 useCookie 值。

選項

Cookie composable 接受多個選項,可讓您修改 cookie 的行為。

大多數選項將直接傳遞到 cookie 套件。

maxAge / expires

使用這些選項來設定 cookie 的到期時間。

maxAge:指定要作為 Max-Age Set-Cookie 屬性值的數字(以秒為單位)。給定的數字將透過向下捨入轉換為整數。預設情況下,未設定最大期限。

expires:指定要作為 Expires Set-Cookie 屬性值的 Date 物件。預設情況下,未設定到期時間。大多數用戶端會將此視為「非持久性 cookie」,並會在退出網頁瀏覽器應用程式等條件下將其刪除。

cookie 儲存模型規範指出,如果同時設定了 expiresmaxAge,則 maxAge 優先,但並非所有用戶端都可能遵守此規則,因此如果兩者都設定,它們應指向相同的日期和時間!
如果 expiresmaxAge 均未設定,則 cookie 將僅限於會話,並在使用者關閉瀏覽器時移除。

httpOnly

指定 HttpOnly Set-Cookie 屬性boolean 值。當為真值時,會設定 HttpOnly 屬性;否則不會設定。預設情況下,未設定 HttpOnly 屬性。

將此設定為 true 時請小心,因為相容的用戶端將不允許用戶端 JavaScript 在 document.cookie 中看到 cookie。

secure

指定 Secure Set-Cookie 屬性boolean 值。當為真值時,會設定 Secure 屬性;否則不會設定。預設情況下,未設定 Secure 屬性。

將此設定為 true 時請小心,因為如果瀏覽器沒有 HTTPS 連線,相容的用戶端將不會在未來將 cookie 送回伺服器。這可能會導致 hydration 錯誤。

partitioned

指定 Partitioned Set-Cookie 屬性的 boolean 值。當為真值時,會設定 Partitioned 屬性,否則不會設定。預設情況下,未設定 Partitioned 屬性。

這是一個尚未完全標準化的屬性,未來可能會變更。這也表示許多用戶端可能會忽略此屬性,直到他們理解它為止。更多資訊可以在提案中找到。

domain

指定 Domain Set-Cookie 屬性的值。預設情況下,未設定網域,大多數用戶端會認為 cookie 僅適用於目前網域。

path

指定 Path Set-Cookie 屬性的值。預設情況下,路徑被視為 「預設路徑」

sameSite

指定 SameSite Set-Cookie 屬性booleanstring 值。

  • true 會將 SameSite 屬性設定為 Strict,以進行嚴格的同站強制執行。
  • false 將不會設定 SameSite 屬性。
  • 'lax' 會將 SameSite 屬性設定為 Lax,以進行寬鬆的同站強制執行。
  • 'none' 會將 SameSite 屬性設定為 None,以進行明確的跨站 cookie。
  • 'strict' 會將 SameSite 屬性設定為 Strict,以進行嚴格的同站強制執行。

有關不同強制執行層級的更多資訊,請參閱 規範

encode

指定一個將用於編碼 cookie 值的函數。由於 cookie 的值具有有限的字元集(且必須是簡單的字串),因此可以使用此函數將值編碼為適合 cookie 值的字串。

預設編碼器是 JSON.stringify + encodeURIComponent

decode

指定一個將用於解碼 cookie 值的函數。由於 cookie 的值具有有限的字元集(且必須是簡單的字串),因此可以使用此函數將先前編碼的 cookie 值解碼為 JavaScript 字串或其他物件。

預設的解碼器是 decodeURIComponent + destr

如果此函式拋出錯誤,則會將原始、未解碼的 cookie 值作為 cookie 的值傳回。

預設值

指定一個函式,該函式會傳回 cookie 的預設值。此函式也可以傳回 Ref

唯讀

允許存取 cookie 值,但不允許設定它。

監看

指定 watch cookie ref 資料的 booleanstring 值。

  • true - 將監看 cookie ref 資料變更及其巢狀屬性(預設)。
  • shallow - 將僅監看 cookie ref 資料變更的頂層屬性
  • false - 將不監看 cookie ref 資料變更。
當 cookie 變更時,使用 refreshCookie 手動重新整理 useCookie 值。

範例 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

<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>

API 路由中的 Cookie

您可以使用 h3 套件中的 getCookiesetCookie 在伺服器 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 }
})
文件 > 範例 > 進階 > 使用 Cookie中閱讀和編輯即時範例。