【问题标题】:how to automatically map path to component如何自动将路径映射到组件
【发布时间】:2018-11-20 01:58:26
【问题描述】:

Vue 2.5、vuex3、vue cli 3

我正在尝试在 vue 中定义路由,我是否必须为每个路径指定组件,假设我有 50 个组件,那么我必须为所有这 50 个组件定义路径,例如路径 aaa - 组件 aaa,路径 bbb - 组件 bbb,路径 ccc - 组件 ccc。?所有路径都与组件名称相同,那么我最终得到了一长串路由定义?

我可以用某种通配符定义路由,这样它就可以尝试根据路径自动查找组件,假设路径名与组件名相同?为简单起见,假设我只有 1 个级别,所有 50 个组件都在组件文件夹中,名称与路径相同。如何避免必须为每条路线定义?

【问题讨论】:

  • 这是一个非常有趣的问题。我也想知道这是否可行。

标签: vue-router


【解决方案1】:

您可以通过组件工厂动态获取组件。

例如,这可以是您的router.js 模块:

import Vue from 'vue';
import Router from 'vue-router';
import ViewFactory from '@/ViewFactory';

Vue.use(Router);

export default new Router({
  mode: 'history',
  routes: [
    {
      path: '**',  // wildcard route
      name: 'view-factory',
      component: ViewFactory
    }
  ]
});

这就是 ViewFactory:

<template>
  <div>
    <component :is="component" />
  </div>
</template>
<script>
import { mapState } from 'vuex'
import Default from '@/components/Default';
import aaa from '@/components/aaa';
import bbb from '@/components/bbb';
import bbb from '@/components/ccc';

export default {

  components: {
    Default,
    aaa,
    bbb,
    ccc
  },

  computed: {
    component () {
      // Get last path part, equals component name
      let component = this.$route.path.split('/').slice(-1);

      // Fallback component
      if (Object.keys(this.$options.components).indexOf(component) === -1) {
        component = 'Default';
      }

      // Return component name
      return component;
    }
  }

}
</script>

this.$route.path发生变化,需要重新加载数据时,别忘了注意ViewFactory中的路径,之后调用reload方法:

watch: {
  // call again the method if the route changes
  '$route': 'load'
},

有关此主题的更多信息:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-10
    • 2015-12-17
    • 2021-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多