Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to redirect to a different url inside the vue-router beforeRouteEnter hook?

Tags:

I am building an admin page with Vue.js 2 and I want to prevent unauthenticated users from accessing the /admin route and redirect them to /login. For that I have used the In-Component Guard beforeRouteEnter in the Admin component like follows

... beforeRouteEnter(to, from, next) {   if(userNotLogedIn) {     this.$router.push('/login');   } } 

The problem here is that this is not defined in beforeRouteEnter hook. So what's the proper way to access $router and redirect to a different url in this case ?

like image 788
Abdelaziz Mokhnache Avatar asked Aug 15 '17 21:08

Abdelaziz Mokhnache


People also ask

How do I redirect my Vue router?

When a user navigates to the /home route, say it should always redirect them to the / route, thereby showing the HomePage . This can be done via redirects: const routes = [ { path: '/', name: 'Home', component: HomePage, }, { path: '/home', redirect: '/', } ];

How do I redirect a page to another page in Vue?

You can use $router. push({ name: "yourroutename"}) or just router. push("yourroutename") now to redirect.

Can Vue router open a link in a new tab?

to open a Vue Router link in a new tab, we can call the $router. resolve method to get the full URL from the route name, path, parameter and query values. Then we can use window. open to open the URL in a new tab.


1 Answers

The documentation states that:

The beforeRouteEnter guard does NOT have access to this, because the guard is called before the navigation is confirmed, thus the new entering component has not even been created yet.

You can redirect to another page by calling next like this:

beforeRouteEnter(to, from, next) {   if(userNotLogedIn) {     next('/login');   } } 

Here is another way to accomplish the same result: So instead of using beforeRouteEnter on each protected route, you could define protected routes in your router configuration using a meta property, then use beforeEach hook on all the routes and check for protected routes and redirect to login page when needed:

let router = new Router({       mode: 'history',       routes: [         {       path: '/profile',       name: 'Profile',       component: Profile,       meta: {         auth: true // A protected route       },     },         {       path: '/login',       name: 'Login',       component: Login, // Unprotected route     },   ] })  /* Use this hook on all the routes that need to be protected  instead of beforeRouteEnter on each one explicitly */  router.beforeEach((to, from, next) => {       if (to.meta.auth && userNotLoggedIn) {     next('/login')   }       else {     next()   }     })  // Your Vue instance new Vue({   el: '#app',   router,   // ... }) 
like image 101
Ikbel Avatar answered Oct 27 '22 01:10

Ikbel