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

Nuxt 3:如何在组合式函数(composable)中获取Cookie?

解决方案

在Nuxt里直接用浏览器原生的localStorage,会因为服务端渲染的特性被迫手动判断客户端环境。推荐用Nuxt官方提供的**useLocalStorage组合式函数**,它会自动处理服务端和客户端的环境差异,完全不用写process.client。

修改后的代码

// composables/useUser.ts
export const useUser = () => {
  // 用useLocalStorage创建响应式的存储对象,自动同步到localStorage
  const authToken = useLocalStorage('auth_token', '')
  const userInfo = useLocalStorage('user', {})

  const info = async () => {
    const config = useRuntimeConfig();

    try {
      // 直接取authToken.value就行,不用手动调用localStorage.getItem
      const { data } = await useFetch(
        `${config.public.baseURL}/users/info`,
        {
          method: "GET",
          headers: { Authorization: `Bearer ${authToken.value}` },
        }
      );

      if (data.value?.user) {
        // 赋值给userInfo.value,自动同步到localStorage
        userInfo.value = data.value.user;
      }
    } catch (error) {
      console.log(error);
    }
  };

  return { info, userInfo };
};

为什么这方法管用?

  • useLocalStorage是Nuxt 3内置的工具,服务端运行时会用内存暂存数据,到客户端自动同步到浏览器的localStorage,不用自己写环境判断逻辑。
  • 它返回的是响应式的ref对象,改value就自动更新存储,读取直接取value就行,符合组合式函数的使用习惯。

如果用Cookie存令牌

要是你的认证令牌存在Cookie里,用Nuxt内置的useCookie也能解决问题,同样不用手动判断环境:

// composables/useUser.ts
export const useUser = () => {
  const authToken = useCookie('auth_token')

  const info = async () => {
    const config = useRuntimeConfig();

    try {
      const { data } = await useFetch(
        `${config.public.baseURL}/users/info`,
        {
          method: "GET",
          headers: { Authorization: `Bearer ${authToken.value}` },
        }
      );

      if (data.value?.user) {
        // 要把用户信息存Cookie的话,也用useCookie创建对象
        const userCookie = useCookie('user')
        userCookie.value = data.value.user;
      }
    } catch (error) {
      console.log(error);
    }
  };

  return { info };
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 16:05:26