Vue Route Middleware
Make complex global route middleware logic look easy and readable!
Installation:
npm i vue-route-middlewareBasic Usage:
Set middleware meta key to your route and add our component to any vue router guard hook.
import VueRouteMiddleware from 'vue-route-middleware';
...
const Router = new VueRouter({
mode: 'history',
routes: [{
path: '/dashboard',
name: 'Dashboard',
component: Dashboard,
meta: {
middleware: (to, from, next) => {
let auth = fakeUser.isLogged();
if(!auth){
next({ name: 'Login' });
}
}
}
}]
});
...
Router.beforeEach(VueRouteMiddleware());NOTICE: Middleware function will retrieve all the variables normally passed to the router guards
Example: (to, from, next) in case of beforeEach or (to, from) in case of afterEach guard.
Chain middlewares with an array of functions:
Example:
NOTICE: If function returns false then the middleware chain will break and no longer execute.
Separated middleware file example:
./route/middleware/auth.js
router.js
Advanced:
Another way to define middlewares is to pass them in the object as the first parameter to VueRouteMiddleware function and pass an array of middleware key names to the meta of the route.
Example:
This way we can differentiate middlewares that will be applied with different guards.
For example you want to add tracking middleware to afterEach guard:
Example:
At the example above beforeEach guard will apply chained AuthMiddleware and PaymentMiddleware ignoring the TrackingMiddleware that will be applied on afterEach guard.
Credits:
Last updated
Was this helpful?