具有路由查询的VueJS渲染动态组件

时间:2020-04-30 17:20:57

标签: vue.js

我试图根据通过单击选项卡产生的路线查询来呈现不同的组件。我尝试了动态组件方法,但是它仅在初始负载下有效。当我通过单击更改路线查询的选项卡进行切换时,它不会更改为其他组件。下面是我的代码和文件

Show.vue

<div>
    <b-container fluid class="bg-white">
        <b-row class="topTab types" v-if="$refs.chart">
          <b-col
            :class="{ active: currentTab === index }"
            v-for="(tabDisplay, index) in $refs.chart.tabDisplays"
            :key="index"
          >
            <router-link
              :to="{ query: { period: $route.query.period, tab: index } }"
            >
              {{ tabDisplay }}
            </router-link>
          </b-col>
        </b-row>
      </b-container>
      <component v-bind:is="currentExample" ref="chart" />
</div>

export default {
    props: {
      group: String,
      cp: String,
      name: String,
      id: [Number, String]
    },
    computed: {
      currentExample() {
        return () =>
          import(
            `@/components/Trend/example/Charts/${this.group}/${this.id}/Base.vue`
          );
      },
    }
}

下面是摘要上方使用的组件

Base.vue

<template>
  <component v-bind:is="currentData"> </component>
</template>

<script>
export default {
  data: function() {
    return {
      tabDisplays: {
        1: "example1",
        2: "example2",
        3: "example3",
        4: "example4",
        5: "example5",
        6: "example6"
      }
    };
  },
  computed: {
    currentData() {
      return () =>
        import(
          `@/components/Trend/example/Charts/${this.$route.params.group}/${
            this.$route.params.id
          }/Tab${this.$route.query.tab === "6" ? "6" : "1-5"}.vue`
        );
    }
  }
};
</script>

我希望我单击 example6 链接。它将在@/components/Trend/example/Charts/${this.group}/${this.id}/Tab6.vue

上显示我的<component>

2 个答案:

答案 0 :(得分:0)

动态组件:is期望标识符不是完全成熟的组件。

您应该在父组件的components属性下导入该组件,然后使用计算出的属性仅获取标识符。

components: {
    'comp{group}{id}{tab}': () => import(
          `@/components/Trend/example/Charts/{group}/{id}/Tab{tab}.vue`)
}

注意:{group}{id}{tab}只是您实际值的占位符。您需要全部导入。

并使用currentData仅获取标识符:

computed: {
  currentData() {
   return `comp${this.$route.params.group}${this.$route.params.id}{this.$route.query.tab === "6" ? "6" : "1-5"}`
  }
}

答案 1 :(得分:0)

我已经通过简单解决了它。

Base.vue

<template>
  <component v-bind:is="currentData"> </component>
</template>

<script>
import Tab from "@/components/Trend/example/Charts/abc/1/Tab1-5.vue";
import Tab6 from "@/components/Trend/example/Charts/abc/1/Tab6.vue";

export default {
  computed: {
    currentData() {
      if (this.$route.query.tab === "6") {
        return Tab6;
      } else {
        return Tab;
      }
    }
  }
};
</script>

我的结构使我在这个级别上简单明了