vue.js - 是否可以根据父组件的道具在 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>
解决方案
由于扩展与混入相同,您需要传递一个动态混入,为此您需要两个组件,假设我们有组件 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
推荐阅读
- java - 如何将数据从重复列表数据转换为组数据列表
- r - 如何将两个 actionButton 与两个单独的闪亮观察事件一起使用?
- android - 自定义组件不再正确呈现
- python - 如何将我的 python 后端连接到我的 HTML 前端以创建用于双散列的 GUI?任何其他创建 GUI 的方法?
- asp.net-core-2.2 - Asp.Net Core 远程验证属性不调用
- apache-spark - 如何在从 Spark 会话中读取文件时传递 s3 存储桶区域
- c# - 如何进行循环以在 ItemsSource 的基础上添加新的 ComboBox?
- python - 为什么这段代码的输出不是二维形式而是一维形式?
- ionic4 - 如何使用 *ngFor 创建带有卡片的水平滚动?
- unetstack - 将噪声函数添加到通道模型