我有一个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>
答案 0 :(得分:0)
由于扩展了与mixin相同的功能,因此您需要传递一个动态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作为道具,我将所有图表作为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>
第二个组件仅具有选项props,并调用了renderChart函数。 ==> 2
发生了什么事?
ChartWrapper组件通过chartType属性接收图表类型,在 created 钩子中,如果存在chartType,则将图表(由VueCharts [this.chartType]解析)分配给Chart组件作为混合除了reactProp, 我还将图表数据传递给Chart组件。
最后,调用ChartWrapper组件:
<ChartWrapper chartType="Bar"/>
代码沙箱上的实时示例:https://codesandbox.io/s/vue-template-w9r8k
答案 1 :(得分:0)
您还可以选择以下选项:仅扩展折线图并使用所需的图表类型更新图表的配置,并对其进行更新以更改其类型。
<script>
import { Line, mixins } from 'vue-chartjs';
const { reactiveProp } = mixins;
export default {
extends: Line,
name: "LineChart",
mixins: [reactiveProp],
props: {
options: { type: Object },
chartType: { type: String }
},
mounted () {
this.renderChart(this.chartData, this.options);
},
watch: {
options: {
deep: true,
handler () {
this.$data._chart.options = this.options;
this.updateChart();
}
},
chartType (newVal) {
this.$data._chart.config.type = newVal;
this.updateChart()
}
},
methods: {
updateChart () {
this.$data._chart.update();
},
}
}
</script>