[Vuejs]-How to use $router.push in Vue-router?

3👍

You can do this with route navigation guards.

Here’s a contrived example using beforeEach (runs before every route):

router.beforeEach(async (to, from, next) => {
  const response = await axios.get(...);
  if (response.data.isGood) {
    next();
  } else {
    next({ name: 'home' });
  }
});

This would run an async call before navigating to each route, and then check the response data. If everything is good, the navigation proceeds. Otherwise, the user is redirected back to the home route.

You can do this for individual routes with beforeEnter:

{
    path: '/',
    name: 'home',
    component: Home,
    async beforeEnter(to, from, next) {
      // same axios call & next usage as above example
    }
}

👤Dan

Leave a comment