user3541631
user3541631

Reputation: 4008

Vue: Redirect an user on logout depeding on which type of page it is

I use navigation guards to not allow users to visit administration pages if is not authenticated.

router.beforeEach(function(to, from, next){
  if (to.meta.requiresAuth && !store.getters.isAuthenticated) {
    next({name: 'site-login'});
  }
  else {
    next()
  }
});

requiresAuth is used as meta on administration page, and isAuthenticated ia a getter that check in a store(Vuex) the state of the user.

When a user clicks on a Logout button, I want to check where the user is. If it is on and administration page redirect to / if it is on a normal page, just reload the current page.

I want to use something similar to above.

 <button @click="logout">Logout</button>

 methods: {
      logout() {
        this.$store.dispatch('logout');
      }
    }

Upvotes: 0

Views: 2402

Answers (1)

Shaya Ulman
Shaya Ulman

Reputation: 1651

Create a special route for logout, and dispatch the logout action from there:

{
  path: '/logout',
  name: 'logout',
  beforeEnter (to, from, next) {
    store.dispatch('logout').then(() => {
    if (from.meta.requiresAuth) {
        return next('/');
    }
      location.reload();
    }
  }
},

Logout by redirecting the user to this page:

<button>
  <router-link to="/logout">Logout</router-link>
</button>

Upvotes: 1

Related Questions