大家可能遇到过这种情况,全局使用一个用户信息放到store中。在公共的侧边栏组件中,请求了一次用户信息,但在其他组件中调取不到。原因可能是加载顺序问题。在其他组件中,在pinia请求后端数据之前,就使用了store中的数据,导致没获取到值。所以我们要做的是,在所有的组件中共享store的值,就算开始没调取到,但当在当全局组件从后端获取到数据后,也能实时的在其他下组件中响应。
1. 创建 Store:首先,你需要创建一个 Pinia store 来存储用户信息。
// store/user.js
import { defineStore } from 'pinia';
export const useUserStore = defineStore('user', {
state: () => ({
userInfo: null,
}),
actions: {
async fetchUserInfo() {
try {
const response = await fetch('/api/user/info');
this.userInfo = await response.json();
} catch (error) {
console.error('Failed to fetch user info:', error);
}
},
},
});
2. 在应用中使用 Store:在你的应用的入口文件中,安装并创建 Pinia 实例。
// main.js
import { createApp } from 'vue';
import { createPinia } from 'pinia';
import App from './App.vue';
const app = createApp(App);
const pinia = createPinia();
app.use(pinia);
app.mount('#app');
3. 在组件中使用 Store:在你的组件中,使用 Pinia store 并在组件创建时获取用户信息。
<script setup>
import { useUserStore } from '@/stores/user';
const userStore = useUserStore();
// 在组件挂载时获取用户信息
onMounted(async () => {
if (!userStore.userInfo) {
await userStore.fetchUserInfo();
}
});
</script>
4. 响应式更新:由于 Pinia store 是响应式的,一旦 userInfo 被更新,所有使用了 userInfo 的组件都会自动更新。
如果你在其他组件中遇到了在 Pinia 请求后端数据之前就使用了 store 中的数据的问题,你可以采取以下措施:
使用 watch 或 computed:在组件中使用 watch 或 computed 来响应 userInfo 的变化。
<script setup>
import { computed } from 'vue';
import { useUserStore } from '@/stores/user';
const userStore = useUserStore();
const userInfo = computed(() => userStore.userInfo);
</script>
在模板中使用条件渲染:在模板中使用 v-if 来确保数据已经加载后再渲染相关内容。
<template>
<div v-if="userStore.userInfo">
<!-- 用户信息已加载,显示内容 -->
</div>
</template>
在路由守卫中获取数据:如果你使用 Vue Router,你可以在路由守卫中获取用户信息,以确保在进入路由之前用户信息已经加载。
router.beforeEach(async (to, from, next) => {
const userStore = useUserStore();
if (!userStore.userInfo) {
await userStore.fetchUserInfo();
}
next();
});
确保你的组件在使用用户信息之前检查它是否已经加载。如果你的应用依赖于用户信息,你可能需要在应用的顶层或者在路由守卫中获取这些信息,以确保在渲染组件之前用户信息已经可用。