Joseph
Joseph

Reputation: 101

Vue Lifecycle — which happens before page renders?

Using Vue 2, I want to run a check before any page elements are rendered, to determine whether the user is signed in and if so, redirect them to another page.

Looking at the Vue Lifecycle, it's my understanding that beforeMount is first in this cycle. However, the page still appears for half a second before redirecting (in my case, to Dashboard)

beforeMount() {
  firebase.auth().onAuthStateChanged((user) => {
    if (user) {  
      this.$router.push({ name: 'Dashboard'})
    }
  });
}

I've tried other Lifecycle options and none of the others work either. What am I doing wrong?

Upvotes: 0

Views: 976

Answers (2)

Mojtaba
Mojtaba

Reputation: 651

You have to use Guard for this. you have to check auth before going to route on router.js file. you can use beforeEnter into your route path.

read more about that here: https://router.vuejs.org/guide/advanced/navigation-guards.html#per-route-guard

Upvotes: 0

Maverick Fabroa
Maverick Fabroa

Reputation: 1173

Looking at the Vue's lifecycle diagram:

beforeCreate and created hooks are earlier than beforeMount. You should use either one of them.

Upvotes: 1

Related Questions