vue.js - 是否可以根据父组件的 props 在扩展 : property, 中动态添加图表类型?

标签 vue.js vue-chartjs

我有一个 vue Chartjs 组件,它导入整个 vue-chartjs 库。我的想法是,是否可以以某种方式传递我想要的图表类型并将其添加到“extends: VueCharts.charttype?”中。在我提供的示例中,它扩展了 VueCharts.Line,我需要动态插值此属性,从 props 传递。该图表类型是否有可能动态地来自父级 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>

最佳答案

由于扩展与 mixins 相同,因此您需要传递一个动态 mixin,为了做到这一点,您需要两个组件,假设我们有组件 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 作为 prop,我将所有图表作为 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 props 和调用的 renderChart 函数。 ==>2

发生了什么?

ChartWrapper组件通过chartType属性接收图表类型,在created钩子(Hook)中,如果chartType存在,则将图表(由VueCharts[this.chartType]解析)分配给Chart组件作为mixin除了reactiveProp之外, 我还将图表数据传递给图表组件。

最后调用ChartWrapper组件:

<ChartWrapper chartType="Bar"/>

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

关于vue.js - 是否可以根据父组件的 props 在扩展 : property, 中动态添加图表类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56663447/

相关文章:

css - 将样式描述传递给子组件

javascript - Vue <template> 标记在迭代列表时未按预期运行

vue.js - 使用 Vue 路由器时如何在 VueJS 组件之间传递数据?

javascript - Chartjs 与 Vue,条形图边框半径不起作用

javascript - Vue ChartJS 默认禁用数据集

javascript - Vue "on-change"方法不适用于复选框

vue.js - 在Vue中: How do you implement the cell-class-name and row-class-name in the el-table of ElementUI?

vue.js - 使用 ChartJS 通过 Vue 获得 "Maximum call stack size exceeded"

javascript - Vue-chartjs:即使数据没有改变也重新渲染图表

javascript - Vue-图表.js : a chart doesn't begin from zero