Skip to content

useCookies

universal-cookie 的封装。

¥Wrapper for universal-cookie.

提示

与 Nuxt 3 一起使用时,不会自动导入此函数,而是使用 Nuxt 的内置 useCookie()。如果你想使用 VueUse 中的函数,请使用显式导入。

¥When using with Nuxt 3, this functions will NOT be auto imported in favor of Nuxt's built-in useCookie(). Use explicit import if you want to use the function from VueUse.

Available in the @vueuse/integrations add-on.

安装

¥Install

bash
npm i universal-cookie@^7

用法

¥Usage

常见用法

¥Common usage

vue
<script>
import { useCookies } from '@vueuse/integrations/useCookies'
import { defineComponent } from 'vue'

export default defineComponent({
  setup() {
    const cookies = useCookies(['locale'])
    return {
      cookies,
    }
  },
})
</script>

<template>
  <div>
    <strong>locale</strong>: {{ cookies.get('locale') }}
    <hr>
    <pre>{{ cookies.getAll() }}</pre>
    <button @click="cookies.set('locale', 'ru-RU')">
      Russian
    </button>
    <button @click="cookies.set('locale', 'en-US')">
      English
    </button>
  </div>
</template>

选项

¥Options

使用 vuecomposer-api 访问和修改 cookie。

¥Access and modify cookies using vue composition-api.

默认情况下,你应该在 setup() 内使用它,但此函数也适用于其他任何地方。

¥By default, you should use it inside setup(), but this function also works anywhere else.

ts
const { get, getAll, set, remove, addChangeListener, removeChangeListener } = useCookies(['cookie-name'], { doNotParse: false, autoUpdateDependencies: false })

dependencies(可选)

¥dependencies (optional)

让你可以选择指定组件所依赖的 cookie 名称列表或应触发重新渲染的 cookie 名称列表。如果未指定,它将在每次 cookie 更改时渲染。

¥Let you optionally specify a list of cookie names your component depend on or that should trigger a re-render. If unspecified, it will render on every cookie change.

options(可选)

¥options (optional)

  • doNotParse(布尔值=假):无论如何不要将 cookie 转换为对象。作为默认值传递给 get/getAll 方法。

    ¥doNotParse (boolean = false): do not convert the cookie into an object no matter what. Passed as default value to get/getAll methods.

  • autoUpdateDependencies(布尔值=假):自动添加曾经提供给 get 方法的 cookie 名称。如果为 true 那么你不需要关心提供的 dependencies

    ¥autoUpdateDependencies (boolean = false): automatically add cookie names ever provided to get method. If true then you don't need to care about provided dependencies.

cookies(可选)

¥cookies (optional)

让你提供一个 universal-cookie 实例(默认创建一个新实例)

¥Let you provide a universal-cookie instance (creates a new instance by default)

有关 通用 cookie api 文档 中可用方法的信息

¥Info about methods available in the universal-cookie api docs

createCookies([req])

使用请求创建 universal-cookie 实例(默认为 window.document.cookie)并返回 useCookies 函数以及提供的通用 cookie 实例

¥Create a universal-cookie instance using request (default is window.document.cookie) and returns useCookies function with provided universal-cookie instance