Search code examples
javascriptvue.jsvuejs2vue-routerlifecycle

VueJS lifecycle order when combined with router


I need to run an async initialize method when my app starts. so I did it inside beforeCreate of App.vue as below.

app.vue:

export default {
  ...
  beforeCreate () {
    console.log('before create app.vue')
  }
}

Also, I need to check a condition before entering any route, so I did it inside beforeEach of router.

main.js:

router.beforeEach((to, from, next) => {
  if (condition) {
    console.log('router before each')
  }
})

The problem is I need to check the condition after my initialization is done, but, when I launch my app, the condition is checked before the initialization and my output is:

router before each

before create app.vue

What am I missing? and how can I fix this?


Solution

  • here is how I solved it in vue3 but you can use a similar approach... basically don't mount the app until the initialization is completed. In my case the authCheck in the initialization function you mention full source

    import useFirebaseAuth from "./hooks/firebase-auth";
    
    const { authCheck  } = useFirebaseAuth();
    
    const app = createApp(App).use(IonicVue);
    
    authCheck()
      .then(() => {
        app.use(router);
        return router.isReady();
      })
      .then(() => {
        app.mount("#app");
      });