primevue-mirror/components/lib/chart/Chart.vue

121 lines
3.0 KiB
Vue
Raw Normal View History

2022-09-06 12:03:37 +00:00
<template>
2023-05-02 07:18:02 +00:00
<div class="p-chart" v-bind="ptm('root')">
<canvas ref="canvas" :width="width" :height="height" @click="onCanvasClick($event)" v-bind="{ ...canvasProps, ...ptm('canvas') }"></canvas>
2022-09-06 12:03:37 +00:00
</div>
</template>
<script>
2023-05-02 07:18:02 +00:00
import BaseComponent from 'primevue/basecomponent';
2022-09-06 12:03:37 +00:00
export default {
name: 'Chart',
2023-05-02 07:18:02 +00:00
extends: BaseComponent,
2022-09-06 12:03:37 +00:00
emits: ['select', 'loaded'],
props: {
type: String,
data: null,
options: null,
plugins: null,
width: {
type: Number,
default: 300
},
height: {
type: Number,
default: 150
2022-12-08 11:04:25 +00:00
},
canvasProps: {
type: null,
default: null
2022-09-06 12:03:37 +00:00
}
},
2022-09-14 11:26:01 +00:00
chart: null,
2022-09-06 12:03:37 +00:00
watch: {
/*
* Use deep watch to enable triggering watch for changes within structure
* otherwise the entire data object needs to be replaced to trigger watch
*/
data: {
handler() {
this.reinit();
},
deep: true
},
type() {
this.reinit();
},
options() {
this.reinit();
}
},
2022-09-14 11:26:01 +00:00
mounted() {
this.initChart();
},
beforeUnmount() {
if (this.chart) {
this.chart.destroy();
this.chart = null;
}
},
2022-09-06 12:03:37 +00:00
methods: {
initChart() {
import('chart.js/auto').then((module) => {
if (this.chart) {
this.chart.destroy();
this.chart = null;
}
if (module && module.default) {
this.chart = new module.default(this.$refs.canvas, {
type: this.type,
data: this.data,
options: this.options,
plugins: this.plugins
});
}
this.$emit('loaded', this.chart);
});
},
getCanvas() {
return this.$canvas;
},
getChart() {
return this.chart;
},
getBase64Image() {
return this.chart.toBase64Image();
},
refresh() {
if (this.chart) {
this.chart.update();
}
},
reinit() {
this.initChart();
},
onCanvasClick(event) {
if (this.chart) {
const element = this.chart.getElementsAtEventForMode(event, 'nearest', { intersect: true }, false);
const dataset = this.chart.getElementsAtEventForMode(event, 'dataset', { intersect: true }, false);
if (element && element[0] && dataset) {
2022-09-14 11:26:01 +00:00
this.$emit('select', { originalEvent: event, element: element[0], dataset: dataset });
2022-09-06 12:03:37 +00:00
}
}
},
generateLegend() {
if (this.chart) {
return this.chart.generateLegend();
}
}
}
2022-09-14 11:26:01 +00:00
};
2022-09-06 12:03:37 +00:00
</script>
<style>
.p-chart {
position: relative;
}
</style>