javascript—尝试在vue路由器中加载多个模块作为中间件是行不通的

lmyy7pcs  于 2021-09-23  发布在  Java
关注(0)|答案(0)|浏览(237)

在我的spa中的vue路由器内,我希望能够在需要时加载多个模块,目前只加载一个模块。我想分离代码,而不是将所有代码都转储到一个文件中,然后失去跟踪。

// folder 
middleware
- index.js
- modules
-- guest.js
-- auth.js
-- locale.js
-- othemodule.js
-- ...

中间件/module/auth.js(其中一个)

export default function auth({ next, store }) {
   if (store.state.auth.authenticated) {
      return next()
   } else {
      return  next({name: 'login'})
   }
}

routes/routes.js

{ 
    path: 'login', name: 'login', component: page('Auth/Login.vue'),
    meta: { 
        layout : 'auth', 
        auth : {
            middleware: 'guest'// this will work
            middleware: ['guest', 'locale', 'other module']// how I want to use it
        }
    }
}

routes/index.js

import Modules from '../middleware/index.js'
const middlewareModules = Modules;

function middlewarePipeline (context, middleware, index) {
    const nextMiddleware = middleware[index]
    if(!nextMiddleware){
        return context.next 
    }
    return () => {
        const nextPipeline = middlewarePipeline(
            context, middleware, index + 1
        )
        nextMiddleware({ ...context, next: nextPipeline })
    }
}

router.beforeEach(async (to, from, next) => {

    const middleware = middlewareModules[to.meta.auth.middleware];

    if (!middleware) {
        return next()
    }

    const context = {
        to,
        from,
        next,
        store
    }

    return middleware.default({
        ...context,
        next: middlewarePipeline(context, middleware, 1)
    })

}

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题