一、vue3echarts封裝
import { defineComponent, watchEffect } from "vue";
import * as echarts from "echarts";
export default defineComponent({
props: {
/** echarts 配置 */
option: {
type: Object,
default: null
},
/** echarts 樣式 */
style: {
type: Object,
default: null
},
/** echarts 點擊事件 */
onClick: {
type: Function,
default: null
}
},
setup(props, { emit }) {
const chartInstance = ref(null);
const init = () => {
if (chartInstance.value) {
return;
}
const chart = echarts.init(chartInstance.value);
chart.setOption(props.option);
if (props.onClick) {
chart.on("click", params => {
props.onClick(params);
});
}
watchEffect(() => {
chart.setOption(props.option || {});
});
chart.resize();
};
onMounted(() => {
init();
});
onBeforeUnmount(() => {
if (chartInstance.value) {
chartInstance.value.dispose();
}
});
return {
chartInstance,
init
};
},
render() {
return ();
}
});
Vue-echarts是一個基於ECharts的封裝組件,可以非常方便地將ECharts的圖表組件嵌入Vue中進行構建,同時也簡化了我們使用ECharts的各項複雜操作,開發人員無需關心底層的實現,只需要專註於業務的開發即可。該代碼由如上封裝,有option、style、onClick三個props屬性,用於接收對應的圖表配置,樣式以及事件處理函數。代碼中watchEffect監聽option,實時更新圖表數據。onMounted調用init函數實例化echarts。最後通過render渲染一個div即可。
二、vue3echarts如何處理後端數據
Vue3echarts 接收來自後端的數據和 echarts 配置,將它們傳遞給 MyCharts 組件,使後者將圖表渲染到頁面。後端如果傳遞數據就作為 component 和 props。我們需要將這些數據傳遞給 component 的 props。
以下是 MyCharts.vue 文件:
<template>
<div class="bar-chart">
<div class="chart-container" ref="chart">原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/158333.html
微信掃一掃
支付寶掃一掃