Vue3 中引用 Echarts 图表模板
使用步骤:
①赋值模板内容:将以下代码CV到 .vue 组件中。
②替换option图表配置项:将Echarts官网提供的图表代码中的option配置项部分复制到 updateChart方法的option对象中。(注:到这里图表就可以显示出来了)。
③将图表数据变活:根据自己的需要将option配置项中的数据提取到props中 以便从父组件传入。
<template>
<div ref="pieRef" :style="{ height: height }"></div>
</template>
<script setup>
import * as echarts from 'echarts';
import { onBeforeUnmount, onMounted, ref } from 'vue';
const props = defineProps({
// 图表容器的宽度(暂未使用)
width: {
type: [Number, String],
default: '200px'
},
// 图标容器的高度
height: {
type: [Number, String],
default: '200px'
},
// 其它需要从父组件传入的图表数据...
})
// ref
const pieRef = ref(null)
// 图表实例
let myChart = null
// 初始化图标
const initChart = () => {
if(pieRef.value) {
myChart = echarts.init(pieRef.value)
updateChart()
}
}
// 更新图表数据
const updateChart = () => {
if(myChart){
let option = {
// 将官网的option内容粘贴到这里即可
};
myChart.setOption(option);
}
}
// 重绘图表
const handleResize = () => {
if(myChart) {
myChart.resize()
}
}
// 钩子 - 初始渲染图表 和添加监听器(监听视口缩放的变化)
onMounted(() => {
initChart()
window.addEventListener('resize', handleResize)
})
// 钩子 - 清楚事件监听器 和 销毁图表
onBeforeUnmount(() => {
window.removeEventListener('resize', handleResize)
if (myChart) {
myChart.dispose()
}
})
</script>
<style lang="scss" scoped>
</style>

被折叠的 条评论
为什么被折叠?



