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:
middleware: [
(to, from, next) => {
let auth = fakeUser.isLogged();
if(!auth){
next({ name: 'Login' });
return false; // if false is returned, middleware chain will break!
}
},
(to, from, next) => {
let hasPaied = fakeUser.madePayment();
if(!hasPaied){
next({ name: 'Payment' });
}
}
]
NOTICE: If function returns false then the middleware chain will break and no longer execute.
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.
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:
import AuthMiddleware from './route/middleware/auth';
import PaymentMiddleware from './route/middleware/payment';
import TrackingMiddleware from './route/middleware/tracking';
...
meta: {
// define all applied middleware to the route
middleware: [ 'AuthMiddleware', 'PaymentMiddleware', 'TrackingMiddleware' ]
}
...
Router.beforeEach(VueRouteMiddleware({ AuthMiddleware, PaymentMiddleware }));
// Pass the tracking function to afterEach guard
Router.afterEach(VueRouteMiddleware({ TrackingMiddleware }));
At the example above beforeEach guard will apply chained AuthMiddleware and PaymentMiddleware ignoring the TrackingMiddleware that will be applied on afterEach guard.