Skip to content

Instantly share code, notes, and snippets.

@manuelgeek
Forked from acfatah/index.js
Created April 16, 2021 09:20
Show Gist options
  • Save manuelgeek/e895dbcc6cc68f5cb85a24aad079f226 to your computer and use it in GitHub Desktop.
Save manuelgeek/e895dbcc6cc68f5cb85a24aad079f226 to your computer and use it in GitHub Desktop.
Quasar Vue Router Middleware Pipeline Example
// router/index.js
import Vue from 'vue'
import VueRouter from 'vue-router'
import routes from './routes'
import middlewarePipeline from './middleware-pipeline'
Vue.use(VueRouter)
/*
* If not building with SSR mode, you can
* directly export the Router instantiation
*/
export default function (/* { store, ssrContext } */ { store }) {
const Router = new VueRouter({
scrollBehavior: () => ({ x: 0, y: 0 }),
routes,
// Leave these as is and change from quasar.conf.js instead!
// quasar.conf.js -> build -> vueRouterMode
// quasar.conf.js -> build -> publicPath
mode: process.env.VUE_ROUTER_MODE,
base: process.env.VUE_ROUTER_BASE
})
/**
* Run the middleware(s) using the beforeEach hook
*/
Router.beforeEach((to, from, next) => {
if (!to.meta.middlewares) return next()
let middlewares = to.meta.middlewares
let context = { to, from, next, store }
return middlewares[0]({
...context,
next: middlewarePipeline(context, middlewares, 1)
})
})
return Router
}
// router/middleware-pipeline.js
/**
* A stack of different middlewares ran in series
* Link: https://blog.logrocket.com/vue-middleware-pipelines/
*/
function middlewarePipeline (context, middlewares, index) {
let middleware = middlewares[index]
if (!middleware) return context.next
return () => {
let nextMiddleware = middlewarePipeline(
context, middlewares, index + 1
)
middleware({ ...context, next: nextMiddleware })
}
}
export default middlewarePipeline
// router/middlewares.js
/**
* Auth middleware example.
*/
export function auth (/* { to, from, next, store } */ { next, store }) {
if(!store.getters.auth) {
return next({ name: 'login' })
}
return next()
}
// router/routes.js
import auth from './middlewares'
const routes = [
// ...
{
path: '/login',
name: 'login',
component: Login
},
// An example of route using auth middleware
{
path: '/dashboard',
name: 'dashboard',
component: Dashboard,
meta: {
middlewares: [ auth ]
},
}
// ...
]
export default routes
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment