vue实现多个echarts根据屏幕大小变化而变化实例
前言
有如下页面需求:在一个页面展示多个echarts图表,并且根据屏幕大小变化而变化。
实例
可以封装成组件使用,以增加代码复用性
// myCharts.vue
 <template>
 <div class="charts-comps" ref="charts"></div>
</template>
<script>
import echarts from 'echarts'
export default {
 name: 'myCharts',
 props: {
 type: {
  type: String,
  default: ''
 }
 },
 data () {
 return {
  resizeTimer: null,
  myChart: null
 }
 },
 methods : {
 init () {
  let myChart = echarts.init(this.$refs.charts);
  this.myChart = myChart;
  myChart.setOption({
	 xAxis: {
  type: 'category',
  boundaryGap: false,
  data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
	 },
	 yAxis: {
	  type: 'value'
	 },
	 series: [{
	  data: [820, 932, 901, 934, 1290, 1330, 1320],
	  type: 'line',
	  areaStyle: {}
	 }]
	 });
 }
 }
 mounted () {
 this.init(); // 初始化图表
 let _this = this;
 window.addEventListener('resize', function () { 
  if (_this.resizeTimer) clearTimeout(_this.resizeTimer);
  _this.resizeTimer = setTimeout(function () {
  _this.myChart.resize();
  }, 100)
 })
 }
}
</script>
<style lang="less" scoped>
 .charts-comps{
 width: 100%;
 height: 100%;
 }
</style>
这样就可以在需要用到的地方使用了
// index.vue
<template>
 <my-charts class="charts-comps" ref="charts" v-for="item in dataList" :key="item"></my-charts>
</template>
<script>
import myCharts from './myCharts'
export default {
 name: 'test',
 components: {myCharts},
 data () {
 return {
 dataList: ['test1','test2','test3','test4']
 }
 }
 }
 </script>
关键代码解析
let _this = this;
window.addEventListener('resize', function () { 
 ...
})
在myCharts组件中去监听窗口大小变化,这样可以针对每一个图表很方便的resize()重绘图表(Echarts.resize()是echarts的对图表进行重新绘制的方法)。这里使用window.addEventListener而不使用window.onresize的原因是:window.onresize绘覆盖掉前面定义的方法,而只执行最后一个,导致图表只有最后一个重绘了,而window.addEventListener避免了这个问题。
if (_this.resizeTimer) clearTimeout(_this.resizeTimer);
_this.resizeTimer = setTimeout(function () {
 _this.myChart.resize();
}, 100)
结合 函数防抖(debounce) 避免在窗口大小变化时频繁的进行图表的resize()。在处理复杂的function时可以很大限度的提高性能。实现原理就是对要执行的目标方法延时处理,设置一个定时器,当再次执行相同方法时(窗口大小变化时会被频繁的侦听到onresize),若前一个定时任务还未执行完,则清除掉定时任务,重新定时。这样当屏幕大小在100毫秒之内没有再次变化时才会对Echarts进行resize(),当然时间段可以根据自身需要设置长一点。
补充知识:vue+echarts 同页面多个echarts图表,明明宽度设置的都是100%,却只有第一个生效以及如何实现自适应
问题描述
三个echarts图表,明明宽度设置的都是100%,却只有第一个生效以及如何实现自适应
解决办法
1.初始化时需要加上,确保操作的是最新的DOM
this.$nextTick(_ => {  
   
});
2.echarts图表自适应实现,需要在渲染图表后加上
window.addEventListener("resize", function() {        
 myChart.resize();      
});
完整如下:
以上这篇vue实现多个echarts根据屏幕大小变化而变化实例就是长沙网络推广分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持狼蚁SEO。
编程语言
- ThinkPad 笔记本如何调节LCD屏幕亮度
 - Dreamweaver制作网页打开特效教程
 - Win10 Mobile 10586升级后无限重启怎么办 硬重启帮您
 - Win8系统提示音频设备有问题有一个或多个音频服
 - Xbox One版Win10首个预览版9月份发布
 - 如何在textarea文本输入区内实现换行
 - Win10 Build 9901系统更新 预览版新版本下载
 - McAfee Framework存在远程格式串处理漏洞
 - Win10家庭版今日(7月30)正式在中国官方商城开卖
 - Win10 Mobile预览版更新完10536.1000后才收到10536.100
 - Win10 RS2更新了什么-Win10 RS2最终版本号1704首曝
 - Windows7如何查看回收站对应的文件夹有哪些方法
 - Win10让Charms栏回归桌面的方法教程
 - 取消Windows XP系统开机启动画面的小技巧
 - win8系统怎么下载安装USB百兆网卡?
 - XP系统下磁盘空间变少了怎么办?XP系统磁盘空间