vue-router 构建动态路由

构建动态路由,无需在文件到router/index.js中import

router/index.js:

{
    path: '/routerPath',
    component: Layout,
    hidden: true,
    children: [
      {
        path: ':fileName',
        component: xxxComponent
      },
      {
        path: ':floder/:fileName',
        component: xxxComponent
      },
      {
        path: ':project/:floder/:fileName',
        component: xxxComponent
      }
    ]
  }

xxxComponent 文件:

<template>
    <component :is="comp"></component>
</template>
// 
<script>

  export default {
    name: 'xxxFile',
    props: ['name'],
    data() {
      let project = this.$route.params.project || '',
          folder = this.$route.params.folder || '',
          fileName = this.$route.params.fileName || '', path = '';
      if (project && folder && fileName ) {
        path =  project + '/' + folder + '/' + fileName;
      } else if(folder && fileName) {
        path =  project + '/' + fileName;
      } else {
        path =  fileName;
      }
      window.localStorage.setItem("path", path);
      return {
        compName: this.name
      }
    },
    computed: {
      comp: function () {
        let path = window.localStorage.getItem("path");
         try {
           return require(`@/routerPath/${path}`);
         }catch(err)  {
           return require(`@/routerPath/error/404`);
         }
      }
    },
    methods: {
      // todo methods
    }
  }

</script>

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容