一、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 (
<div ref="chartInstance" style={this.style}></div>
);
}
});
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"></div>
</div>
</template>