vue-根据路由列表动态配置 router 列表

说明

后台中存储着某个用户相对应的路由列表,需要根据路由列表在项目中动态生成 router列表。

// 后台数据
[
  {
    name: '数据管理',
    path: '/data/manager',
    component: 'manage.vue'
  }
]
// 前端项目
this.$router.push('/data/manager')  // 即可渲染 manage.vue

实现

使用 this.$router.addRoute(routeConfig)

const routerList = [
  {
    name: '数据管理',
    path: '/data/manager',
    component: 'manage.vue'
  }
]
routerList.forEach(async (item) => {
  const com = await import(`@/views/${item.component}`) // 引入 src/views/manage.vue 文件
  item.component = com.default
  this.$router.addRoute(item)  // 添加到 vue 的 router 列表中
})
this.$router.push('/data/manager')

ERROR

Template string failing with Cannot read property 'range' of null

https://github.com/babel/babel/issues/10904

  1. 卸载 babel-eslint

    npm uninstall babel-eslint

  2. 安装 @babel/eslint-parser

  3. 在 eslint 配置文件中将 babel-eslint 替换为 @babel/eslint-parser

    // .eslintrc.js
    module.exports = {
      root: true,
      env: {
        node: true
      },
      extends: [
        'plugin:vue/essential',
        '@vue/standard'
      ],
      parserOptions: {
        parser: '@babel/eslint-parser'  // 修改这里
      },
      rules: {
        'no-console': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
        'no-debugger': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
        'prefer-const': 'off',
        'quotes': 'off',
        'semi': 'off',
        'space-before-function-paren': 'off',
        'comma-dangle': 'off',
        "template-curly-spacing": ["error", "never"]
      }
    }