README
Viddleware
This is a small library which lets you use route middleware in vue-router very nicely.
Installation
npm i viddleware
or, if you use yarn
yarn add viddleware
Example
Assume we have a dashboard and a page. Only admin can access the dashboard and for the other page user has to be adult and user must have a mobile number. Below is the implementation.
main.js
import Vue from 'vue'
import router from './router'
const vue = new Vue({
el: '#app',
router
});
router.js
import Vue from 'vue'
import VueRouter from 'vue-router'
import routerMiddleware from 'viddleware'
// Middleware
import auth from './middleware/admin.js'
import adult from './middleware/adult.js'
import mobile './middleware/mobile.js'
// Pages
import dashboard from './pages/dashboard.vue'
import aPage from './pages/aPage.vue'
Vue.use(VueRouter);
const router = new VueRouter({
routes: [{
name: '/dashboard',
component: dashboard,
meta: {
middleware: admin
}
},
{
name: '/a-page',
component: aPage,
meta: {
middleware: [adult, mobile]
}
}
]
});
export default routerMiddleware(router);
./middleware/admin.js
export default function(route, from, next) {
// User should be an admin
if (!userIsAdmin()) {
// User is not an admin
return next(false);
}
// Ok
next();
}
./middleware/adult.js
export default function(route, from, next) {
// User should be over 18
if (!isUserAdult()) {
// User is under 18
return next(false);
}
// Ok
next();
}
./middleware/mobile.js
export default function(route, from, next) {
// User should have a mobile number
if (!mobileExists()) {
// User does not have a mobile number
return next(false);
}
// Ok
next();
}
Typescript
./middleware/admin.ts
import {Middleware} from 'viddleware'
const admin: Middleware = (route, from, next) => {
if (!userIsAdmin()) {
return next(false);
}
next();
};
export default admin;
Note: Middleware is just an alias to the NavigationGuard