在数据展示层面总会用上 echarts,今天更新一波 vue3 中 echarts 组件封装文档。
涉及到 vue3 和 echarts5
vue3 文档
echarts5 文档
npm install echarts@5.4.1 --save
<template>
<div :id="echartId" :style="chartStyle" />
</template>
<script setup>
import * as echarts from 'echarts'
import { ref, onBeforeMount, onMounted, defineProps } from 'vue'
const props = defineProps({
chartStyle: {
type: Object,
default: () => ({
width: '600px',
height: '400px'
})
},
chartOption: {
type: Object,
default: () => ({}),
required: true
}
})
const drawChart = () => {
const echart = echarts.init(document.getElementById(echartId.value))
echart.setOption(props.chartOption, {
notMerge: true // 不和之前的 option 合并
})
window.addEventListener('resize', () => {
echart.resize({
animation: { duration: 300 }
})
})
}
const echartId = ref(null)
onBeforeMount(() => {
echartId.value = `echarts-id-${parseInt(Math.random() * 1000000)}`
})
onMounted(() => {
drawChart()
})
</script>
在传入的数据发生变更时,要让图表也跟着变化,所以要在组件中添加 watch 监听,那我们修改一下。
...
import { ref, watch, onBeforeMount, onMounted, defineProps } from 'vue'
...
watch(
props.chartOption,
{ deep: true },
() => {
drawChart()
}
)
...