# @dargmuesli/nuxt-cookie-control 中文文档

规范地址：https://npmcn.com/package/%40dargmuesli/nuxt-cookie-control/

版本：10\.0\.0
npm 元数据更新时间：2026-11-09T13:32:55.651Z
中文译文更新时间：2026-11-11T11:42:14.100Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40dargmuesli/nuxt-cookie-control
原文对照：https://npmcn.com/package/%40dargmuesli/nuxt-cookie-control/?lang=original
源码仓库：https://github.com/dargmuesli/nuxt-cookie-control

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：124 kB，105 个文件
- 模块格式：ES Module
- TypeScript 类型：包内自带
- Node.js 要求：^22\.22\.3 \|\| ^24\.15\.0 \|\| \>=26\.0\.0
- 运行依赖：4 个
- 首次发布：2022-04-04T12:58:48.707Z
- 最新版本发布：2026-11-09T13:32:55.323Z
- 近 30 天下载量：39732（2026-10-12 至 2026-11-10，npm 官方下载统计）
- 已发布版本数：237（近 12 个月 48 个）

## 中文简介

Nuxt Cookie 控制模块

## 安装

```sh
npm install @dargmuesli/nuxt-cookie-control
```

也可以使用：`pnpm add @dargmuesli/nuxt-cookie-control`、`yarn add @dargmuesli/nuxt-cookie-control`、`bun add @dargmuesli/nuxt-cookie-control`

## README

# Nuxt Cookie 控件

[![ci status](https://img.shields.io/github/actions/workflow/status/dargmuesli/nuxt-cookie-control/ci.yml)](https://github.com/dargmuesli/nuxt-cookie-control/actions/workflows/ci.yml) [![npm version](https://badgen.net/npm/v/@dargmuesli/nuxt-cookie-control/latest)](https://npmjs.com/package/@dargmuesli/nuxt-cookie-control) [![npm downloads](https://badgen.net/npm/dm/@dargmuesli/nuxt-cookie-control)](https://npmjs.com/package/@dargmuesli/nuxt-cookie-control)

![nuxt-cookie-control](https://drive.google.com/a/broj42.com/uc?id=19sFguJo7SKUvmH4xu9DhK9ZXzR6oWLX8)

翻译为:ar, az, be, bg, ca, cs, da, de, en, es, fi, fr, hr, hu, id, it, ja, km, ko, it, nl, no, oc, pt-BR, pl, ro, r, ru, sk, sv, tr, uk and zh

✅ Vue 3 支持

QQ 对于 Nuxt 2, 请使用 nuxt- cookie- control < 3. 0.0

自从Dario Ferderber继续从事 [gitlab.com/broj42/nuxt-cookie-控制](https://gitlab.com/broj42/nuxt-cookie-control)一定要读读读读!

## 开始

[![Stackblitz](https://developer.stackblitz.com/img/open_in_stackblitz.svg)](https://stackblitz.com/github/dargmuesli/nuxt-cookie-control?file=playground%2Fapp.vue)

### 安装

```bash
npx nuxi@latest module add cookie-control
```

### 配置

```javascript
// nuxt.config.js

modules: [
  '@dargmuesli/nuxt-cookie-control'
],
cookieControl: {
  // typed module options
}

// or

modules: [
  ['@dargmuesli/nuxt-cookie-control', {
    // untyped module options
  }]
]
```

### 使用量

```html
<!-- app.vue -->

<template>
  <CookieControl locale="en" />
</template>

<script setup lang="ts">
const {
  cookiesEnabled,
  cookiesEnabledIds,
  isConsentGiven,
  isModalActive,
  moduleOptions,
} = useCookieControl()

// example: react to a cookie being accepted
watch(
  () => cookiesEnabledIds.value,
  (current, previous) => {
    if (
      !previous?.includes('google-analytics') &&
      current?.includes('google-analytics')
    ) {
      // cookie with id `google-analytics` got added
      window.location.reload() // placeholder for your custom change handler
    }
  },
  { deep: true },
)
</script>
```

```ts
//  plugins/analytics.client.ts

// example: initialization based on enabled cookies
const cookieControl = useCookieControl()

if (cookieControl.cookiesEnabledIds.value.includes('google-analytics')) {
  initGoogleAnalytics() // placeholder for your custom initialization
}
```

### 程序化 Cookie 注册( Kit)

其他 Nuxt 模块可以在设置阶段使用 `@dargmuesli/nuxt-cookie-control/kit` 输出。 这在饼干由外部模块管理时是有用的,这些模块需要自己在饼干控制系统中注册.

```ts
// modules/my-analytics-module.ts

import { defineNuxtModule } from '@nuxt/kit'
import { addCookieControl, CookieType } from '@dargmuesli/nuxt-cookie-control/kit'

export default defineNuxtModule({
  setup() {
    addCookieControl(
      {
        id: 'google-analytics',
        name: 'Google Analytics',
        description: 'Tracks user interactions and page views.',
        src: 'https://www.googletagmanager.com/gtag/js',
      },
      CookieType.OPTIONAL
    )
  }
})
```

#### `addCookieControl(cookie, type, nuxt?)`

在模块设置时将饼干添加到饼干控制配置中.

-   **饼干** `Cookie` - 要注册的饼干对象
-   **类型** `CookieType` - 类别: `CookieType.NECESSARY` 或者说 `CookieType.OPTIONAL`
-   **纳克特** `Nuxt` (可选) - Nuxt 实例(如果不提供则自动从上下文中检测)

**注释:**

-   在模块设置阶段必须调用, 而非运行时
-   通过检查所有类别的现有饼干ID来防止饼干的重复
-   如果一个具有相同ID的饼干已经存在, 则悄悄返回

## API 密码

### 模块选项

```javascript
// Position of cookie bar.
// 'top-left', 'top-right', 'top-full', 'bottom-left', 'bottom-right', 'bottom-full'
barPosition: 'bottom-full',

// Position of the cookie control button.
// 'top-left', 'top-right', 'bottom-left', 'bottom-right'
// @default 'bottom-right'
controlButtonPosition: 'bottom-right',

// Switch to toggle if clicking the overlay outside the configuration modal closes the modal.
closeModalOnClickOutside: true,

// Component colors.
// If you want to disable colors set colors property to false.
colors: {
  barBackground: '#000',
  barButtonBackground: '#fff',
  barButtonColor: '#000',
  barButtonHoverBackground: '#333',
  barButtonHoverColor: '#fff',
  barTextColor: '#fff',
  checkboxActiveBackground: '#000',
  checkboxActiveCircleBackground: '#fff',
  checkboxDisabledBackground: '#ddd',
  checkboxDisabledCircleBackground: '#fff',
  checkboxInactiveBackground: '#000',
  checkboxInactiveCircleBackground: '#fff',
  controlButtonBackground: '#fff',
  controlButtonHoverBackground: '#000',
  controlButtonIconColor: '#000',
  controlButtonIconHoverColor: '#fff',
  focusRingColor: '#808080',
  modalBackground: '#fff',
  modalButtonBackground: '#000',
  modalButtonColor: '#fff',
  modalButtonHoverBackground: '#333',
  modalButtonHoverColor: '#fff',
  modalOverlay: '#000',
  modalOverlayOpacity: 0.8,
  modalTextColor: '#000',
  modalUnsavedColor: '#fff',
},

// The cookies that are to be controlled.
// See detailed explanation further down below!
cookies: {
  necessary: [],
  optional: [],
}

// The milliseconds from now until expiry of the cookies that are being set by this module.
cookieExpiryOffsetMs: 1000 * 60 * 60 * 24 * 365, // one year

// Names for the cookies that are being set by this module.
cookieNameIsConsentGiven: 'ncc_c',
cookieNameCookiesEnabledIds: 'ncc_e',

// Options to pass to nuxt's useCookie
cookieOptions: {
  path: '/',
  sameSite: 'strict',
},

// Switch to toggle the "accept necessary" button.
isAcceptNecessaryButtonEnabled: true,

// Switch to toggle the button that opens the configuration modal.
isControlButtonEnabled: true,

// Switch to toggle the concatenation of target cookie ids to the cookie description.
isCookieIdVisible: false,

// Switch to toggle the inclusion of this module's css.
// If css is set to false, you will still be able to access your color variables.
isCssEnabled: true,

// Switch to toggle the css variables ponyfill.
isCssPonyfillEnabled: false,

// Switch to toggle the separation of cookie name and description in the configuration modal by a dash.
isDashInDescriptionEnabled: true,

// Switch to toggle the blocking of iframes.
// This can be used to prevent iframes from adding additional cookies.
isIframeBlocked: false,

// Switch to toggle the modal being shown right away, requiring a user's decision.
isModalForced: false,

// "Decline all" in the modal removes all cookies by default (which will re-open the cookie bar).
// Set this to true to decline all optional cookies and accept necessary cookies.
declineAllAcceptsNecessary: false,

// The locales to include.
locales: ['en'],

// Translations to override.
localeTexts: {
  en: {
    save: 'Remember',
  }
}
```

#### 饼干

所有财产,包括 `{ en: ... }` 值是一个可变属性,它只能指定字符串(`'...'`)或其他地点(`{ de: ..., uk: ... }`) (中文(简体) ).

```javascript
{
  description: {
    en: 'This cookie stores preferences.'
  },
  id: 'p', // use a short cookie id to save bandwidth and prefixes to separate
  isPreselected: false // `true` is not GDPR compliant! This flag does not enable any cookies, it only preselects the cookie's modal toggle. The default is `false`.
  name: {
    en: 'Preferences' // you always have to specify a cookie name (in English)
  },
  links: {
    'https://example.com/privacy': 'Privacy Policy',
    'https://example.com/terms': 'Terms of Service',
  },
  src: 'https://example.com/preferences/js?id=<API-KEY>',
  targetCookieIds: ['xmpl_a', 'xmpl_b'],
}
```

### 组件槽

#### 栏

```html
<CookieControl>
  <template #bar>
    <h2>Bar title</h2>
    <p>Bar description (you can use $cookies.text.barDescription)</p>
    <n-link>Go somewhere</n-link>
  </template>
</CookieControl>
```

#### 模式

```html
<CookieControl>
  <template #modal>
    <h2>Modal title</h2>
    <p>Modal description</p>
  </template>
</CookieControl>
```

#### 饼干

```html
<CookieControl>
  <template #cookie="{ cookie }">
    <h3 v-text="cookie.name" />
    <span v-html="cookie.description" />

    <div v-if="cookie.targetCookieIds">
      <b>Cookie ids: </b>
      <span v-text="cookie?.targetCookieIds?.join(', ')" />
    </div>
  </template>
</CookieControl>
```

#### 框架

```html
<CookieIframe>
  <template #iframe>
    Content to display if iframes are blocked.
  </template>
</CookieIframe>
```

#### 控制按钮

```html
<CookieIframe>
  <template #controlButton>
    <svg xmlns="http://www.w3.org/2000/svg" width="512" height="512" viewBox="0 0 512 512"><path fill="currentColor" d="M247.2 17c-22.1-3.1-44.6.9-64.4 11.4l-74 39.5c-19.7 10.5-35.6 27-45.4 47.1l-36.7 75.6c-9.8 20.1-13 42.9-9.1 64.9l14.5 82.8c3.9 22.1 14.6 42.3 30.7 57.9l60.3 58.4c16.1 15.6 36.6 25.6 58.7 28.7l83 11.7c22.1 3.1 44.6-.9 64.4-11.4l74-39.5c19.7-10.5 35.6-27 45.4-47.2l36.7-75.5c9.8-20.1 13-42.9 9.1-64.9l-14.6-82.8c-3.9-22.1-14.6-42.3-30.7-57.9l-60.2-58.3c-16.1-15.6-36.6-25.6-58.7-28.7zM208 144a32 32 0 1 1 0 64a32 32 0 1 1 0-64m-64 192a32 32 0 1 1 64 0a32 32 0 1 1-64 0m224-64a32 32 0 1 1 0 64a32 32 0 1 1 0-64"/></svg>
  </template>
</CookieIframe>
```

### 道具

-   语言 : `['en']`

```html
<CookieControl locale="de" />
```

## 常见问题

### @dargmuesli/nuxt-cookie-control 是什么？

Nuxt Cookie 控制模块

### 如何安装 @dargmuesli/nuxt-cookie-control？

在项目目录运行 npm install @dargmuesli/nuxt-cookie-control，或使用 pnpm add / yarn add / bun add。

### @dargmuesli/nuxt-cookie-control 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @dargmuesli/nuxt-cookie-control 支持 ESM 还是 CommonJS？

以 ES Module 形式发布，推荐使用 import 引入。在 CommonJS 项目中，Node\.js 20\.19\+ / 22\.12\+ 可以直接 require\(\) 不含顶层 await 的 ES Module，更早的版本需要改用动态 import\(\)。

### @dargmuesli/nuxt-cookie-control 需要什么版本的 Node\.js？

package\.json 的 engines 字段要求 Node\.js ^22\.22\.3 \|\| ^24\.15\.0 \|\| \>=26\.0\.0。版本不符时 npm 默认只给出警告，开启 engine-strict 后会拒绝安装。

### @dargmuesli/nuxt-cookie-control 可以商用吗？

@dargmuesli/nuxt-cookie-control 使用 MIT 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### @dargmuesli/nuxt-cookie-control 的下载量有多少？

根据 npm 官方下载统计，@dargmuesli/nuxt-cookie-control 在 2026/10/12 – 2026/11/10 这 30 天内被下载 39,732 次，日均约 1,324 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @dargmuesli/nuxt-cookie-control 还在维护吗？

最新版本 10\.0\.0 发布于 2026/11/09（1 天前）；至今共发布 237 个版本，其中过去 12 个月发布了 48 个；首次发布于 2022/04/04。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

