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

如何在多个Vue组件中复用异步用户获取逻辑?

解决方案

方案1:封装为Vue组合式函数(Composable)

这是Vue 3推荐的复用组件逻辑的方式,能让你在任意组件中快速复用用户数据获取逻辑,无需重复编写代码。

创建一个useAuth.ts文件,把用户数据相关逻辑封装进去:

import { ref } from 'vue';
import type { RouterOutput } from './path-to-your-trpc-router'; // 替换为你的RouterOutput实际路径
import { getLoggedInAccount } from './path-to-getLoggedInAccount'; // 替换为你的函数实际路径

type Account = RouterOutput['auth']['loggedInAccount'];

export function useAuth() {
  const currentAccount = ref<Account>({} as Account);
  const isLoading = ref(false);
  const error = ref<Error | null>(null);

  async function fetchAccount() {
    isLoading.value = true;
    error.value = null;
    try {
      currentAccount.value = await getLoggedInAccount();
    } catch (err) {
      error.value = err as Error;
      console.error('Failed to fetch account:', err);
    } finally {
      isLoading.value = false;
    }
  }

  return {
    currentAccount,
    isLoading,
    error,
    fetchAccount
  };
}

在任意组件中直接使用:

import { useAuth } from './useAuth';
import { onMounted } from 'vue';

const { currentAccount, isLoading, error, fetchAccount } = useAuth();

// 组件挂载时触发获取
onMounted(() => {
  fetchAccount();
});

方案2:使用Pinia全局状态管理

如果你的用户数据需要在多个组件间共享,且希望状态更新能同步到所有使用的组件,用Pinia全局状态管理更合适。

首先创建Pinia的auth store(stores/auth.ts):

import { defineStore } from 'pinia';
import type { RouterOutput } from './path-to-your-trpc-router';
import { getLoggedInAccount } from './path-to-getLoggedInAccount';

type Account = RouterOutput['auth']['loggedInAccount'];

export const useAuthStore = defineStore('auth', {
  state: () => ({
    currentAccount: {} as Account,
    isLoading: false,
    error: null as Error | null
  }),
  actions: {
    async fetchAccount() {
      this.isLoading = true;
      this.error = null;
      try {
        this.currentAccount = await getLoggedInAccount();
      } catch (err) {
        this.error = err as Error;
        console.error('Failed to fetch account:', err);
      } finally {
        this.isLoading = false;
      }
    }
  }
});

在组件中使用:

import { useAuthStore } from '@/stores/auth';
import { onMounted } from 'vue';

const authStore = useAuthStore();

onMounted(() => {
  authStore.fetchAccount();
});

你还可以在App.vue的onMounted钩子中调用一次authStore.fetchAccount(),这样整个应用初始化时就会获取用户数据,所有组件直接使用authStore.currentAccount即可,无需每个组件单独调用。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 12:56:05