Vue2 中使用 Echarts 实现动态折线图带流动光效线条
<p><template>/n <div>/n <div ref='chart' style='height:400px;'></div>/n </div>/n</template>/n/n<script>/nimport echarts from 'echarts';/n/nexport default {/n data() {/n return {/n chart: null,/n option: {/n xAxis: {/n type: 'category',/n data: []/n },/n yAxis: {/n type: 'value'/n },/n series: [{/n type: 'line',/n data: [],/n symbol: 'none',/n lineStyle: {/n width: 2/n },/n areaStyle: {/n color: 'rgba(0, 128, 255, 0.1)'/n },/n markLine: {/n silent: true,/n symbol: 'none',/n label: {/n position: 'middle',/n formatter: '{b}: {c}'/n },/n lineStyle: {/n color: 'rgba(255, 165, 0, 0.6)',/n type: 'solid',/n width: 2/n },/n data: [{/n yAxis: 50/n }]/n }/n }]/n }/n }/n },/n mounted() {/n this.chart = echarts.init(this.$refs.chart);/n this.chart.setOption(this.option);/n this.addData();/n },/n methods: {/n addData() {/n const timeData = new Date().toLocaleTimeString().replace(/^/D*/,'');/n const valueData = Math.floor(Math.random() * 100);/n this.option.xAxis.data.push(timeData);/n this.option.series[0].data.push(valueData);/n this.chart.setOption(this.option);/n this.addEffect(timeData, valueData);/n setTimeout(() => {/n this.addData();/n }, 3000);/n },/n addEffect(timeData, valueData) {/n const effectOption = {/n xAxis: 0,/n yAxis: 0,/n symbolSize: 10,/n color: 'rgba(255, 165, 0, 0.8)',/n effect: {/n show: true,/n period: 6,/n trailLength: 0,/n symbol: 'circle',/n symbolSize: 10/n },/n data: [[timeData, valueData]]/n };/n this.chart.setOption({/n series: [{/n type: 'effectScatter',/n data: effectOption.data,/n symbolSize: effectOption.symbolSize,/n itemStyle: {/n normal: {/n color: effectOption.color/n }/n },/n rippleEffect: effectOption.effect/n }]/n });/n }/n }/n}/n</script>/n/n解析:/n/n1. 在模板中,使用<code>ref</code>属性指定一个<code>div</code>作为折线图的容器。/n/n2. 在<code>data</code>中,定义<code>chart</code>变量为<code>null</code>,表示折线图实例;定义<code>option</code>变量为折线图的配置项,包括<code>xAxis</code>、<code>yAxis</code>和<code>series</code>。/n/n3. 在<code>mounted</code>钩子函数中,使用<code>echarts.init</code>方法初始化折线图实例,并使用<code>setOption</code>方法设置折线图的初始配置项;然后调用<code>addData</code>方法添加数据并刷新折线图,同时调用<code>addEffect</code>方法添加流动光效线条。/n/n4. 在<code>addData</code>方法中,使用<code>new Date().toLocaleTimeString().replace(/^/D*/,'')</code>获取当前时间并格式化为字符串,作为数据的横坐标;使用<code>Math.floor(Math.random() * 100)</code>生成一个0-100之间的随机数,作为数据的纵坐标;然后将数据添加到折线图的配置项中,调用<code>setOption</code>方法刷新折线图,同时使用<code>setTimeout</code>方法定时循环调用<code>addData</code>方法。/n/n5. 在<code>addEffect</code>方法中,定义一个<code>effectOption</code>变量,包括流动光效线条的配置项,然后使用<code>setOption</code>方法添加流动光效线条。其中,<code>effectScatter</code>表示流动光效线条的类型,<code>data</code>表示流动光效线条的数据,<code>symbolSize</code>表示流动光效线条的大小,<code>itemStyle.normal.color</code>表示流动光效线条的颜色,<code>rippleEffect</code>表示流动光效线条的效果。</p>
原文地址: https://www.cveoy.top/t/topic/nmvC 著作权归作者所有。请勿转载和采集!