我正在尝试创建一个在单击按钮时删除 cookie 的函数。我正在使用useCookieNuxt 3 中的函数。由于useCookie提供h3,我尝试使用deleteCookie(h3 中的另一个函数),但这不起作用。我还尝试将过期日期设置为过去:
useCookie('userId', {
expires: new Date().setDate(new Date().getDate() - 1)
})
Run Code Online (Sandbox Code Playgroud)
但这也不起作用。
2023 年 2 月更新:
要删除 Nuxt 3 中的 cookie,我们可以简单地设置它null或undefined:
<script setup>
function logout () {
const authCookie = useCookie('auth')
authCookie.value = null
}
<script>
Run Code Online (Sandbox Code Playgroud)
这将自动删除 cookie,因为在此链接中,Nuxt 将设置maxAge: -1cookie 是否为null或undefined
小智 6
这是 useCookie 在 Nuxt 3 中的工作原理:
获取cookie:
const cookie = useCookie(name, options)
Run Code Online (Sandbox Code Playgroud)
设置cookie:
cookie.value = YOUR_VALUE
Run Code Online (Sandbox Code Playgroud)
删除 cookie
cookie.value = null
Run Code Online (Sandbox Code Playgroud)