由于扩展与 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 属性,并且调用了 renderChart 函数。
==> 2
发生了什么?
ChartWrapper 组件通过chartType prop 接收图表类型,在created 钩子中,如果chartType 存在,则将图表(由VueCharts[this.chartType] 解析)作为mixin 分配给Chart 组件除了 reactiveProp,
我还将图表数据传递给 Chart 组件。
最后调用 ChartWrapper 组件:
<ChartWrapper chartType="Bar"/>
代码沙箱上的实时示例:https://codesandbox.io/s/vue-template-w9r8k