首页 > 解决方案 > 是否可以根据父组件的道具在 extends: 属性中动态添加图表类型?

问题描述

我有一个 vue chartjs 组件,它导入整个 vue-chartjs 库。我的想法是,是否有可能以某种方式传递我想要的图表类型并将其添加到“扩展:VueCharts.charttype?”。在我提供的示例中,它扩展了 VueCharts.Line,我需要动态插值这个属性,从 props 传递。这种图表类型是否有可能动态地来自父道具以及如何?

<script>
import { VueCharts } from "vue-chartjs";

export default {
  extends: VueCharts.Line,
  props: ["chartdata", "options"],
  mounted() {
    this.renderChart(this.chartdata, this.options);
  }
}
</script>
<style scoped>

</style>

标签: vue.jsvue-chartjs

解决方案


由于扩展与混入相同,您需要传递一个动态混入,为此您需要两个组件,假设我们有组件 ChartWrapper :

<template>
  <div>
    <div>{{ chartType }}</div>
    <chart :chart-data="datacollection"/>
  </div>
</template>

<script>
import Chart from "./Chart";
import { VueCharts, mixins } from "vue-chartjs";
const { reactiveProp } = mixins;
export default {
  name: "ChartWrapper",
  components: {
    Chart
  },
  props: {
    chartType: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      datacollection: {
        labels: [this.getRandomInt(), this.getRandomInt()],
        datasets: [
          {
            label: "Data One",
            backgroundColor: "#f87979",
            data: [this.getRandomInt(), this.getRandomInt()]
          },
          {
            label: "Data One",
            backgroundColor: "#f87979",
            data: [this.getRandomInt(), this.getRandomInt()]
          }
        ]
      }
    };
  },
  methods: {
    getRandomInt() {
      return Math.floor(Math.random() * (50 - 5 + 1)) + 5;
    }
  },
  created() {
    if (this.chartType) {
      Chart.mixins = [reactiveProp,VueCharts[this.chartType]];
    }
  }
};
</script>

该组件将chartType 作为道具,我将所有图表作为VueCharts 导入脚本顶部==> 1

第二部分:

<script>
export default {
  props: ["options"],
  mounted() {
    // this.chartData is created in the mixin.
    // If you want to pass options please create a local options object
    this.renderChart(this.chartData, this.options);
  }
};
</script>

第二个组件只有 options 道具,并调用了 renderChart 函数。 ==> 2

怎么了?

ChartWrapper 组件通过chartType prop 接收图表类型,在created hook 中,如果chartType 存在,则将图表(由VueCharts[this.chartType] 解析)作为mixin 分配给Chart 组件,除了reactiveProp,我也传递图表数据到图表组件。

最后调用 ChartWrapper 组件:

<ChartWrapper chartType="Bar"/>

代码沙箱上的实时示例:https ://codesandbox.io/s/vue-template-w9r8k


推荐阅读