构建vue项目以及下载echart这里不再赘述, 有问题可以交流, 感谢指正
<template>
// 准备应该容器, 使用ref属性避免渲染位置混淆
<div ref="chartDom" class="box"></div>
</template>
<script setup>
import { ref, onMounted, watch, useTemplateRef } from 'vue'
import * as echarts from 'echarts'
// 定位ref属性
const chartDom = useTemplateRef("chartDom")
const myChart = ref(null)
// 假设这是响应式的数据源(销量)
const chartData = ref([5, 20, 36, 10, 10, 20])
onMounted(() => {
myChart.value = echarts.init(chartDom.value)
setChartOption()
})
// 封装设置图表的函数
function setChartOption() {
myChart.value.setOption({
title: { text: 'ECharts 动态更新示例' },
tooltip: {},
xAxis: {
data: ['衬衫', '羊毛衫', '雪纺衫', '裤子', '高跟鞋', '袜子'],
},
yAxis: {},
series: [
{
name: '销量',
type: 'bar',
data: chartData.value,
},
],
})
}
// 监听数据变化,更新图表
watch(chartData, () => {
setChartOption()
}, {deep: true})
</script>
<style scoped>
.box {
width: 500px;
height: 500px;
}
</style>