<template> <div class="chart-div" id="chartDiv" style="width:278px;height:300px;float:left"></div> </template> <script setup> import {ref, onMounted, nextTick} from "vue"; import * as echarts from 'echarts'; const chartLightList = ref([ {id: 0, lightLevel: 1, lightValue: 10}, ])//亮度等级-亮度值 const lightLevelList = ref(chartLightList.value.map((i) => { return i.lightLevel }))//亮度等级 const lightValueList = ref(chartLightList.value.map((i) => { return i.lightValue }))//亮度值 /* 踩坑--vue3 echarts实例不能设置响应式(用ref包裹等),否则tooltip会不显示 */ let myChart = (null) const option = ref({ title: { text: '亮度曲线', left: '35%' }, grid: { left: 70 }, xAxis: { type: '', data: lightLevelList.value, name: '环境亮度(传感器)', nameLocation: 'center', nameGap: 25 }, yAxis: { type: 'value', name: '亮度等级', nameLocation: 'center', nameGap: 50 }, tooltip: { trigger: 'axis', formatter: "亮度等级:{b0}<br/> 亮度值:{c0}" }, series: [ { data: lightValueList.value, type: 'line' } ] });//echarts配置项 //监听亮度值实时绘图 const changeLight = (val) => { lightValueList.value = chartLightList.value.map((i) => { return i.lightValue }) option.value.series[0].data = lightValueList.value; /* 踩坑-解决数据变化后实例未实时变化 true==>Cannot read properties of undefined (reading 'type') setOption(option, notMerge, lazyUpdate) notMerge—— 可选,是否不跟之前设置的 option 进行合并,默认为 false,即合并 */ myChart.setOption(option.value, true) } //绘制折线图 const drawChart = () => { myChart = echarts.init(document.getElementById("chartDiv")); option.value && myChart.setOption(option.value); window.onresize = function () { // 自适应大小 myChart.resize(); } } //绘制echarts图 onMounted(() => { // 初始化ECharts实例 nextTick(() => { drawChart() }) }) //保存调亮设置 const doSet = () => { /** * 调用保存调亮设置接口 */ } </script>
复制
踩坑一:vue3 echarts实例不能设置响应式(用ref包裹等),否则tooltip会不显示。
踩坑二:解决数据变化后折线图未实时变化
setOption(option,true)=>解决报错:Cannot read properties of undefined (reading 'type')
setOption(option, notMerge, lazyUpdate)
notMerge—— 可选,是否不跟之前设置的 option 进行合并,默认为 false,即合并
每天进步一点点,慢慢就能遇见更好的自己!