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

Nuxt3如何全局访问Cookie?无需重复声明useCookie

Nuxt3 全局访问UserCookie的实现方案

要在Nuxt3的所有页面和组件中无需重复声明即可访问UserCurrency Cookie,最简洁的方案是通过Nuxt插件封装Cookie逻辑并全局注入。

步骤1:创建全局Cookie插件

在项目的plugins目录下新建文件(比如user-cookie.ts或user-cookie.js),将Cookie的初始化和操作逻辑封装在这里:

export default defineNuxtPlugin(() => {
  // 初始化UserCookie,设置过期时间与默认值
  const UserCurrency = useCookie("UserCurrency", {
    maxAge: 60 * 60 * 24 * 7,
    default: () => ({ code: "USD", name: "US Dollar" })
  });

  // 定义修改Cookie的方法
  const setCurrency = (item: { code: string; name: string }) => {
    UserCurrency.value = item;
    window.location.reload(true);
  };

  // 向全局注入Cookie实例和修改方法
  return {
    provide: {
      userCurrency: UserCurrency,
      setCurrency
    }
  };
});

Nuxt会自动识别plugins目录下的文件并注册,无需额外配置。

步骤2:在组件中直接使用

模板中直接调用

在ProductCard.vue这类组件的模板里,可直接通过$userCurrency访问Cookie值:

<template>
  <card>
    <h3>Product Price : {{ $userCurrency.code }} {{ Cost }}</h3>
  </card>
</template>

Script中调用(含useFetch场景)

在<script setup>里,通过useNuxtApp()获取全局注入的Cookie实例:

<script setup>
const { $userCurrency } = useNuxtApp();
const AllProducts = await useFetch(`SomeApiRoute?currency=${$userCurrency.value.code}`);
</script>

步骤3:改造现有CurrencySwitcher组件

原有的CurrencySwitcher.vue无需重复声明useCookie,直接使用插件提供的全局方法:

<script setup>
const { $setCurrency } = useNuxtApp();

// 复用原有方法逻辑,直接调用全局的setCurrency
const SetCurrency = (item) => {
  $setCurrency(item);
};
</script>

注意事项

  • useCookie在Nuxt3中是跨端兼容的,插件会在服务端和客户端同时执行,不会影响SSR渲染。
  • 如果需要在Pinia状态管理或自定义Composables中使用,同样通过useNuxtApp().$userCurrency获取即可。
  • 避免使用Vue3的全局Mixin方案,Nuxt官方更推荐插件注入的方式来维护全局可访问的逻辑。

内容的提问来源于stack exchange,提问作者Vinay Thakur

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 10:20:42