Kalreg
Kalreg

Reputation: 1012

Vue.js with VueRouter - how to correctly route on user's refresh

I use Vue and VueRouter (and also Vuex but it is not the case here) in my project. Imagine i have 5 files:

  1. main.js - stores all components definitions, imports them from external files and so on.
  2. App.vue - it is main component that stores all other
  3. routes.js - stores all the routing definitions
  4. login.vue - stores login component (login page)
  5. content.vue - stores page component

(quite simplified version but you surely get the idea).

Now if i open my path '/' it should reroute me to '/login' page if i am not logged in and to '/content' when i am logged in. Nothing special here. Now my page works as intended (almost). If I enter in my browser '/content' it tries to render '/content' component with default data (ie userId = -1), then immediately it reroutes me to '/login' page. The '/content' shows just for a second. And it is my problem. I would like to reroute to '/login' without earlier rendering '/content' with default data.

It is obvious that it tries to render '/content' - maybe from cache or something, but since rerouting is my first command in created() it should not mount /content component in app component, but /login.

Any idea how to prevent it? I am aware that i do not attach any code, but i hope it wont be necessery for you to understand the problem and advice any solution because it would need cutting and simpliding a lot of code.

Upvotes: 1

Views: 1418

Answers (2)

Julien J
Julien J

Reputation: 87

Except if the API in the meantime declares that you are no longer authenticated, the router will not be able to refresh itself by the beforeEach method.

Even with a loop method that retrieves data from the API, which will store them in the store as reactive data.

In Vue everything can be reactive, except Vue router

Upvotes: 1

y4h2
y4h2

Reputation: 3383

In your case, I think you should use vue router's beforeEach hook. You can use meta field in router to indicates whether the path need authentication, and do processing in beforeEach function.

I will give the sample code.

import Router from 'vue-router';

const router = new Router({
  routes: [{
    path: '/content',
    meta: {
      auth: true,
    }
  }, {
    path: '/login',
  }]
});


router.beforeEach(async (to, from, next) => {
  if (to.matched.some(m => m.meta.auth)) {

    // user your authentication function
    const isAuth = await getAuthentication;

    if (!isAuth) {
      next('/login');
    }

    next();
  }
})

if your authentication function is not async function, you should remove async/await keywords

Upvotes: 2

Related Questions