Make complex global route middleware logic look easy and readable!
Installation:
npm i vue-route-middleware
Basic Usage:
Set middleware
meta key to your route and add our component to any vue router guard hook.
;...const Router = mode: 'history' routes: path: '/dashboard' name: 'Dashboard' component: Dashboard meta: { let auth = fakeUser; if!auth ; } ;...Router;
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: { let auth = fakeUser; if!auth ; return false; // if false is returned, middleware chain will break! } { let hasPaied = fakeUser; if!hasPaied ; }
NOTICE: If function returns false
then the middleware chain will break and no longer execute.
Separated middleware file example:
./route/middleware/auth.js
{ let auth = fakeUser; if!auth ; return false; }
router.js
;...meta: middleware: AuthMiddleware ...
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:
;;...meta: middleware: 'AuthMiddleware' 'PaymentMiddleware' ...Router;
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:
;;;...meta: // define all applied middleware to the route middleware: 'AuthMiddleware' 'PaymentMiddleware' 'TrackingMiddleware' ...Router;// Pass the tracking function to afterEach guardRouter;
At the example above beforeEach
guard will apply chained AuthMiddleware
and PaymentMiddleware
ignoring the TrackingMiddleware
that will be applied on afterEach
guard.