vue 根据路由参数动态引入组件

vue yekong 1204℃

最近在写一个小项目,每增加一个组件,就增加一个对应的路由页面,这样就会有很多不必要的工作量,比如每增加一个组件,就需要相应的增加一个对应的页面,和一个对应的路由,这样会增加很多不必要的工作量,有没有办法只需要增加组件就可以了,页面根据路由参数自动渲染指定的组件。

路由配置

 {
      path: '/bar/:id',
      name: 'home',
      component: resolve => require(['@/views/bar/page'], resolve),
      meta: {
        requiresAuth: true,
        showPage: true
      }
    },

代码

<template>
  <div class="items">
    <item :title="$route.params.id">
      <component :is="dynamicCom"/>
    </item>
  </div>
</template>

<script>
// 头部
import item from "@/components/item";

export default {
  data() {
    return {
      dynamicCom: null
    }
  },
  components: {
    item,
  },
  created() {
    console.log(this.$route.params.id)
    this.dynamicCom = require(`../../components/bar/${this.$route.params.id}/index.vue`).default
  },
  watch: {},
  mounted() {
  },
  methods: {},
  filters: {}
}
</script>

<style lang="scss" scoped>
.homebody {
  width: 100%;
  position: relative;
  height: 100%;
  background: #09254C;
  display: flex;
  justify-content: flex-start;
  align-items: flex-start;
  flex-wrap: nowrap;
  flex-direction: row;
}

.homemainctop {
  width: 100%;
}

.itembody {
  position: relative;
  width: 100%;
  height: 100%;
}

.items {
  width: 100%;
  height: 100%;
  position: absolute;
  background: #0F75C1;
}

.bars {
  width: 100%;
  height: calc(100% - 100PX);
  position: relative;
}
</style>

喜欢 (0)