【问题标题】:Vue.js 2 multiple routing filesVue.js 2 多个路由文件
【发布时间】:2018-03-17 09:01:24
【问题描述】:

我想开始在大型应用程序上使用 vue.js。该应用程序将有 50 多个模块,每个模块有多个组件。

我的计划是在 components 文件夹下创建子文件夹作为模块,每个文件夹都包含它的相关组件文件。

我不希望 router/index.js 文件中定义数百条路由,因为这将无法管理。

最好在每个模块文件夹中放置一个 routes.js 文件。

这可能吗?如何或有更好的方法。

【问题讨论】:

    标签: module routing vue.js


    【解决方案1】:

    您绝对可以这样做,但最终您需要将它们全部导入到一个 routes.js 文件中。

    本文通过一种解决方案介绍了您的情况:https://medium.com/@disjfa/lets-route-a-vue-app-aa9c3f3dbdf8

    我考虑实现这一点的另一种方法是从每个模块导出一个 const 路由,将它们导入顶级 routes.js,并在 App.vue 中使用该文件。

    祝你好运!

    【讨论】:

      【解决方案2】:

      您可以将每组路由放在自己的文件中,然后导入这些文件并使用扩展运算符合并路由。

      这是一个例子:

      路由器/index.js

      import moduleRoutes1 from "./path/to/moduleRoutes1"
      import moduleRoutes2 from "./path/to/moduleRoutes2"
      
      const router = new Router({
          mode: 'history',
          routes: [
            ...moduleRoutes1,
            ...moduleRoutes2
            //etc. 
      
            //Note '...' here is a "spread operator" and not ellipsis
          ]
      

      路由器/moduleRoutes1

      let VuePage1 = () => import(/* webpackChunkName: MyChunk */ '@/path/to/VuePage1')
      let VuePage2 = () => import(/* webpackChunkName: MyChunk */ '@/path/to/VuePage2')
      
      import moduleRoutes1_1 from "./path/to/moduleRoutes1_1"
      
      export default [
          {
              path: '/some/path/1',
              name: 'pathName1',
              component: VuePage1,
          },
          {
              path: '/some/path/2',
              name: 'pathName2',
              component: VuePage2,
          },
          ...moduleRoutes1_1 //dividing modules further if needed
      ]
      

      路由器/moduleRoutes2

      ... //now it's ellipsis
      You've got the idea
      

      【讨论】:

        【解决方案3】:

        我不知道这是否是使用 JS 本身的最佳方法 我创建了类似的文件

        import Profile from '../views/user/Profile'
        import Login from '../views/user/Login'
        
        export default [
         {
           path: '/',
           name: 'Login',
           component: Login,
           meta: {
              allowAnonymous: true
           }
         },
        {
           path: '/profile',
           name: 'Profile',
           component: Profile,
           beforeEnter: (to, from, next) => {
             if (!store.state.userIsLogged) next({ path: '/', replace: true })
             else next()
           }
         }
        ]
        

        并在 index.js 文件中导入创建和使用扩展运算符的文件

        import UserRouter from './user'
        
        const routes = [
           ...UserRouter,
        ]
        

        任何观察都会说话

        【讨论】:

          猜你喜欢
          • 2018-02-07
          • 1970-01-01
          • 2016-12-11
          • 2019-05-28
          • 1970-01-01
          • 2020-10-17
          • 2019-05-03
          • 2021-07-28
          • 2017-01-12
          相关资源
          最近更新 更多