You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Nuxt.js 3中实现点击按钮删除Cookie?

在 Nuxt3 组件里,useCookie 是响应式的,直接把 Cookie 的值设为 null 就能触发删除操作,这是最简单有效的方式:

// 在组件内定义
const userId = useCookie('userId')

// 点击按钮触发的函数
const deleteUserIdCookie = () => {
  userId.value = null
}

如果你的 Cookie 设置了特定的 path、domain 或者 secure 属性,初始化 useCookie 时必须带上这些参数,否则无法匹配到目标 Cookie:

const userId = useCookie('userId', {
  path: '/admin', // 和设置Cookie时的path一致
  domain: 'yourdomain.com' // 如有设置必须带上
})

const deleteUserIdCookie = () => {
  userId.value = null
}

服务器端删除 Cookie(API/中间件)

如果是在服务器端(比如 server/api 目录或中间件里),使用 h3 的 deleteCookie 时,必须传入 event 对象,并且匹配原 Cookie 的属性:

export default defineEventHandler(event => {
  deleteCookie(event, 'userId', {
    path: '/', // 必须和设置Cookie时的path一致
    // 若设置过domain、secure等,也要对应加上
  })
  return { message: 'Cookie deleted' }
})

为什么你之前的方法无效

  • 修改 expires 选项无效:useCookie 的配置选项(比如 expires)仅在第一次初始化 Cookie 时生效,不会动态修改已存在的 Cookie 的过期时间。
  • h3 deleteCookie 失败:大概率是没传入正确的 event 对象,或者没有匹配原 Cookie 的 path、domain 等属性,导致无法定位到要删除的 Cookie。

内容的提问来源于stack exchange,提问作者Jared Peter

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 06:54:48