如何在初始化 firebase 连接后将 quasar 应用程序挂载到 dom?

How to mount quasar app to dom after firebase connection is initialized?

您好,我如何在与 firebase 建立连接后初始化我的 quasar 应用程序。我需要这样做,因为我的路由守卫会检查用户是否已登录,但如果用户刷新,这会导致 firebase 检查当前用户是否存在,但由于它是异步操作,它最初 returns 为空。我之前已经使用 vue 实现了这一点,我在我的 main.js 文件中完成了这个,但我不确定如何做到这一点是类星体引导文件。

import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import './assets/main.css'

import { authService } from './firebase/config'

let app

authService.onAuthStateChanged(() => {
  if(!app){
    app = createApp(App).use(router).mount('#app')
  }
})

在 main.js 标准 vue 应用程序中,我们等待 Firebase Auth 初始化,只有在 .onAuthStateChanged() 方法触发后,我们才创建 Vue 应用程序。

在 quasar 应用程序中没有 main.js 而是引导文件 运行 在主应用程序启动之前的一些代码。

下面是标准引导文件的样子,但我不确定如何将我的 main.js 转换为可执行引导文件,似乎缺少一些属性,如 mount、createApp 和 use。

// import something here

// "async" is optional!
// remove it if you don't need it
export default async ({ /* app, router, store */ }) => {
  // something to do
}

理想情况下,您创建一个 boot file 用于在 Quasar 项目中初始化 Firebase。

Boot files fulfill one special purpose: they run code before the App’s Vue root component is instantiated while giving you access to certain variables, which is required if you need to initialize a library, interfere with Vue Router, inject Vue prototype or inject the root instance of the Vue app.

使用以下命令创建引导文件:

quasar new boot firebase

这将创建一个引导文件/src/boot/firebase.js

使用 npm(或 yarn)安装 Firebase,然后在启动文件中添加以下代码:

import firebase from 'firebase/app';
import 'firebase/auth';

const firebaseConfig = {...};

if (!firebase.apps.length) {
  firebase.initializeApp(firebaseConfig);
}

export const auth = firebase.auth();

如前所述,引导文件在 Vue 组件实例化之前运行。现在您可以在任何您想要的组件中访问这个 Firebase Auth 实例。

import {auth} from "@/boot/firebase"

auth.onAuthStateChanged((user) => {
  //...
})

这成功了。

export default async ({ app, router, store }) => {
    return new Promise(resolve => {
        const unsubscribe = authService.onAuthStateChanged(() => {
            resolve()
            unsubscribe()
        })
    })
}

这里还有一篇关于quasar开机流程的有用文章https://quasar.dev/quasar-cli/boot-files#quasar-app-flow