最近我開始在我的Vue 3專案中使用Pinia作為全域儲存。我使用Firebase進行用戶身份驗證,並嘗試在Vue初始化之前載入當前用戶。理想情況下,所有與身份驗證相關的內容應該在一個單獨的文件中,使用Pinia Store。不幸的是(與Vuex不同),在我使用任何action之前,Pinia實例需要在Vue實例之前傳遞,我認為這就是問題所在。在首次載入時,儲存中的user
物件短暫為空。
這是綁定使用者的儲存action(使用新的Firebase Web v9 Beta)在auth.js
中:
import { defineStore } from "pinia"; import { firebaseApp } from "@/services/firebase"; import { getAuth, onAuthStateChanged, getIdTokenResult, } from "firebase/auth"; const auth = getAuth(firebaseApp); export const useAuth = defineStore({ id: "auth", state() { return { user: {}, token: {}, }; }, actions: { bindUser() { return new Promise((resolve, reject) => { onAuthStateChanged( auth, async (user) => { this.user = user; if (user) this.token = await getIdTokenResult(user); resolve(); }, reject() ); }); }, // ... }})
這是我的main.js
檔案:
import { createApp } from "vue"; import App from "./App.vue"; import router from "./router"; import { createPinia } from "pinia"; import { useAuth } from "@/store/auth"; (async () => { const app = createApp(App).use(router).use(createPinia()); const auth = useAuth(); auth.bindUser(); app.mount("#app"); })();
如何在其他任何操作發生之前設定使用者?
I figured it out. Had to register the router after the async stuff