We'll try to create and use middlewares for Vue Router in diffetent way, we'll start with the simpliest then dive deeper!
Read More about here, It give us 3 option to work with routes, beforeEnter/beforeLeave/beforeRouteUpdate it's check request before accessing the route then you can decide what to do with it, but you can't triget what's going there in beforeEnter/Leave, you can watch the $route in watch method or in beforeRouteUpdatem a simple example is like this:
const router = new VueRouter({
mode: 'history',
routes: [
{
path: '/dashboard',
component: VueComponent,
beforeEnter: (to, from, next) => {
# to: the route that we want to access to
# from: this route! The route that we're in currently
# next(): Resolve the route
# Here you can do some checking such as if the user is auth or have permission..
if(!isAuth) next({name: 'loginRoute'})
# example two
if(!isAdmin) next({path: 'notFound'})
#example Three
if(!hasPermission) next(error)
next()
}
},
]
})You can check before accessing to desired route or after, like so:
# This will work before accessing to each route
router.beforeEach((to, from, next) => {
next()
})
# This will work after accessing to each route
router.afterEach((to, from) => {
console.log('afterEach')
})You can create a folder called middlewares then inside that you can start add middleware file, like so:
- auth.js
- guest.js
- log.js This is a sample example of adding a middleware as a module, let's take this path middlewares/auth.js:
export default guestMiddleware = (to, from, next) => {
if(!isAuth) return next({ name: 'loginRoute'})
return next({path: '/dashboard'})
}In your routes.js
import guestMiddleware from '/path/to/middlewares/auth.js'
guestMiddleware
const router = new Router({
routes: [{
path: '/dashboard',
name: 'dashboardRoute',
component: DashboardComponent,
meta: {
title: 'The HTML Title tage: welcome to dashboard',
metaTags: [
{
name: 'description',
content: 'some description here.'
}
]
middleware: [
guestMiddleware # You can add many middelwares
]
}
},