vue2、vue3分别配置echarts多图表的同步缩放

这篇具有很好参考价值的文章主要介绍了vue2、vue3分别配置echarts多图表的同步缩放。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

⭐前言

大家好!我是yma16,本文分享在vue2和vue3中配置echarts的多图表同步缩放
背景:
解决echarts的多图表x轴同步联动的问题

⭐使用dataZoom api实现echart的同步缩放

echarts的datazoom api对外暴露
vue2、vue3分别配置echarts多图表的同步缩放

原理:
echarts的实例存在datazoom缩放的方法,
所以只需要在datazoom事件触发其他图表的datazoom即可实现同步缩放

dispatchAction({
    type: 'dataZoom',
    // 可选,dataZoom 组件的 index,多个 dataZoom 组件时有用,默认为 0
    dataZoomIndex: number,
    // 开始位置的百分比,0 - 100
    start: number,
    // 结束位置的百分比,0 - 100
    end: number,
    // 开始位置的数值
    startValue: number,
    // 结束位置的数值
    endValue: number
})

注意:
x轴的范围要一致,不然可能会出现偏移

💖 vue2实现echarts多图表同步缩放

用变量记录echarts的实例,渲染完毕再触发datazoom

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>echarts 滚动事件</title>
		<!-- vue2 生产环境版本,优化了尺寸和速度 -->
		<script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
		<script src="./echarts.js"></script>
	</head>
	<style>
		#app {
			position: absolute;
			height: 100vh;
			width: 100vw;
		}
	</style>
	<body>
		<div id="app">
			<div>
				first
				<div id="first" style="width: 900px;height:400px;"></div>
				second
				<div id="second" style="width: 900px;height:400px;"></div>

				third
				<div id="third" style="width: 900px;height:400px;"></div>
			</div>
		</div>

		<script type="text/javascript">
			const instanceVue = {
				el: '#app',
				name: 'ecahrts',
				data() {
					return {
						firstChart: null,
						secondChart: null,
						thirdChart: null,
						maxNum:1000,
					};
				},
				mounted() {
					
					this.initSecondData()
					this.initThirdData()
					this.initFirstData()
				},
				methods: {
					initFirstData() {

						// 基于准备好的dom,初始化echarts实例
						var myChart = echarts.init(document.getElementById('first'));

						// 指定图表的配置项和数据
						let base = +new Date(1968, 9, 3);
						let oneDay = 24 * 3600 * 500;
						let date = [];
						let data = [Math.random() * 300];
						for (let i = 1; i < this.maxNum; i++) {
							var now = new Date((base += oneDay));
							date.push([now.getFullYear(), now.getMonth() + 1, now.getDate()].join('/'));
							data.push(Math.round((Math.random() - 0.5) * 20 + data[i - 1]));
						}
						const option = {
							tooltip: {
								trigger: 'axis',
								position: function(pt) {
									return [pt[0], '10%'];
								}
							},
							title: {
								left: 'center',
								text: 'Large Area Chart'
							},
							toolbox: {
								feature: {
									dataZoom: {
										yAxisIndex: 'none'
									},
									restore: {},
									saveAsImage: {}
								}
							},
							xAxis: {
								type: 'category',
								boundaryGap: false,
								data: date
							},
							yAxis: {
								type: 'value',
								boundaryGap: [0, '100%']
							},
							dataZoom: [{
									type: 'inside',
									start: 0,
									end: 10
								},
								{
									start: 0,
									end: 10
								}
							],
							series: [{
								name: 'Fake Data',
								type: 'bar',
								symbol: 'none',
								sampling: 'lttb',
								itemStyle: {
									color: 'rgb(255, 70, 131)'
								},
								areaStyle: {
									color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
											offset: 0,
											color: 'rgb(255, 158, 68)'
										},
										{
											offset: 1,
											color: 'rgb(255, 70, 131)'
										}
									])
								},
								data: data
							}]
						};
						// 使用刚指定的配置项和数据显示图表。
						myChart.setOption(option);
						// 监听
						this.firstChart = myChart;
						this.asyncZoom()
					},
					asyncZoom() {
						const that = this
						this.firstChart.on('datazoom', function(params) {
							[that.secondChart, that.thirdChart].forEach(item => {
								console.log('item',item)
								item && item.dispatchAction({ // 触发 dataZoom 事件
									type: 'dataZoom',
									zoomLock: true, // 锁定整个图表的缩放功能
									xAxisIndex: params
										.xAxisIndex, // xAxisIndex 为当前操作的 xAxisIndex,用于确定对应的 xAxis 对象
									yAxisIndex: params
										.yAxisIndex, // yAxisIndex 为当前操作的 yAxisIndex,用于确定对应的 yAxis 对象
									start: params.start, // start 为当前操作的时间范围起始值
									end: params.end // end 为当前操作的时间范围结束值
								});
							})
						})
					},
					initSecondData() {
						// 基于准备好的dom,初始化echarts实例
						const myChart = echarts.init(document.getElementById('second'));
						// 指定图表的配置项和数据
						let base = +new Date(1968, 9, 3);
						let oneDay = 24 * 3600 * 500;
						const date = []
						const yData1 = [Math.random() * 300]
						const yData2 = [Math.random() * 100]
						for (let i = 1; i < this.maxNum; i++) {
							var now = new Date((base += oneDay));
							date.push([now.getFullYear(), now.getMonth() + 1, now.getDate()].join('/'))
							yData1.push(Math.round((Math.random() - 0.5) * 20 + yData1[i - 1]));
							yData2.push(Math.round((Math.random() - 0.5) * 20 + yData2[i - 1]));
						}
						const option = {
							title: {
								text: 'line'
							},
							tooltip: {
								trigger: 'axis'
							},
							legend: {},
							toolbox: {
								show: true,
								feature: {
									dataZoom: {
										yAxisIndex: 'none'
									},
									dataView: {
										readOnly: false
									},
									magicType: {
										type: ['line', 'bar']
									},
									restore: {},
									saveAsImage: {}
								}
							},
							xAxis: {
								type: 'category',
								boundaryGap: false,
								data: date
							},
							yAxis: {
								type: 'value',
								axisLabel: {
									formatter: '{value} °C'
								}
							},
							series: [{
									name: 'Highest',
									type: 'line',
									data: yData1,
									markPoint: {
										data: [{
												type: 'max',
												name: 'Max'
											},
											{
												type: 'min',
												name: 'Min'
											}
										]
									},
									markLine: {
										data: [{
											type: 'average',
											name: 'Avg'
										}]
									}
								},
								{
									name: 'Lowest',
									type: 'line',
									data: yData2,
									markPoint: {
										data: [{
											name: '周最低',
											value: -2,
											xAxis: 1,
											yAxis: -1.5
										}]
									},
									markLine: {
										data: [{
												type: 'average',
												name: 'Avg'
											},
											[{
													symbol: 'none',
													x: '90%',
													yAxis: 'max'
												},
												{
													symbol: 'circle',
													label: {
														position: 'start',
														formatter: 'Max'
													},
													type: 'max',
													name: '最高点'
												}
											]
										]
									}
								}
							]
						};
						myChart.setOption(option);
						this.secondChart = myChart;
					},
					initThirdData() {
						// 基于准备好的dom,初始化echarts实例
						const myChart = echarts.init(document.getElementById('third'));
						// 指定图表的配置项和数据
						let base = +new Date(1968, 9, 3);
						let oneDay = 24 * 3600 * 500;
						const date = []
						const yData1 = [Math.random() * 300]
						for (let i = 1; i < this.maxNum; i++) {
							var now = new Date((base += oneDay));
							date.push([now.getFullYear(), now.getMonth() + 1, now.getDate()].join('/'))
							yData1.push(Math.round((Math.random() - 0.5) * 20 + yData1[i - 1]));
						}
						option = {
							toolbox: {
								show: true,
								feature: {
									dataZoom: {
										yAxisIndex: 'none'
									},
									dataView: {
										readOnly: false
									},
									magicType: {
										type: ['line', 'bar']
									},
									restore: {},
									saveAsImage: {}
								}
							},
							tooltip:{
								trigger:'axis'
							},
							legend: {},
							grid: {
								left: '3%',
								right: '4%',
								bottom: '3%',
								containLabel: true
							},
							xAxis: [{
								type: 'category',
								boundaryGap: false,
								data: date
							}],
							yAxis: [{
								type: 'value',
							}],
							series: [{
									name: 'Direct',
									type: 'bar',
									data: yData1
								}
							]
						};
						myChart.setOption(option);
						this.thirdChart = myChart;
					}
				}
			}
			// 实例化
			new Vue(instanceVue);
		</script>
	</body>
</html>

代码在insidecode,如下运行即可


效果:
vue2、vue3分别配置echarts多图表的同步缩放

💖 vue3实现echarts多图表同步缩放

用state存储echarts实例,渲染完之后触发dataZoom

<template>
  <div>
    <!--    折线图-->
    <div id="first" :style="{ width, height }"></div>
    <!--    柱状图-->
    <div id="second" :style="{ width, height }"></div>
    <div id="third" :style="{ width, height }"></div>
    <div id="fourth" :style="{ width, height }"></div>
  </div>
</template>
<script lang="ts" setup>
  import {  reactive, onMounted } from 'vue';
  import * as echarts from 'echarts';

  const state: any = reactive({
    maxNum: 100,
    // 折线图
    lineChart1: null,
    // 柱状图1
    barChart1: null,
    // 柱状图2
    barChart2: null,
    // 柱状图3
    barChart3: null,
  });

  function asyncZoom() {
    console.log(' state.lineChart1', state.lineChart1);
    state?.lineChart1?.on('datazoom', function (params) {
      [state.barChart1, state.barChart2, state.barChart2, state.barChart3].forEach((item) => {
        console.log('item', item);
        item &&
          item.dispatchAction({
            // 触发 dataZoom 事件
            type: 'dataZoom',
            zoomLock: true, // 锁定整个图表的缩放功能
            xAxisIndex: params.xAxisIndex, // xAxisIndex 为当前操作的 xAxisIndex,用于确定对应的 xAxis 对象
            yAxisIndex: params.yAxisIndex, // yAxisIndex 为当前操作的 yAxisIndex,用于确定对应的 yAxis 对象
            start: params.start, // start 为当前操作的时间范围起始值
            end: params.end, // end 为当前操作的时间范围结束值
          });
      });
    });
  }

  function renderLineChart4(val: any): any {
    // const { setOptions } = useECharts(chartLineRef1 as Ref<HTMLDivElement>);
    const myChart = echarts.init(document.getElementById('fourth'));
    if (!myChart) {
      return;
    }
    // 指定图表的配置项和数据
    let base = +new Date(1968, 9, 3);
    let oneDay = 24 * 3600 * 500;
    const date = [];
    const yData1 = [Math.random() * 300];
    for (let i = 1; i < state.maxNum; i++) {
      var now = new Date((base += oneDay));
      date.push([now.getFullYear(), now.getMonth() + 1, now.getDate()].join('/'));
      yData1.push(Math.round((Math.random() - 0.5) * 20 + yData1[i - 1]));
    }
    const option = {
      toolbox: {
        show: true,
        feature: {
          dataZoom: {
            yAxisIndex: 'none',
          },
          dataView: {
            readOnly: false,
          },
          magicType: {
            type: ['line', 'bar'],
          },
          restore: {},
          saveAsImage: {},
        },
      },
      legend: {},
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true,
      },
      xAxis: [
        {
          type: 'category',
          boundaryGap: false,
          data: date,
        },
      ],
      yAxis: [
        {
          type: 'value',
        },
      ],
      series: [
        {
          name: 'Direct',
          type: 'bar',
          data: yData1,
        },
      ],
    };
    console.log('option', option);
    myChart.setOption(option, true);
    // dom.setOption(option, true);
    state.barChart3 = myChart;
  }

  function renderLineChart3(val: any): any {
    // const { setOptions } = useECharts(chartLineRef1 as Ref<HTMLDivElement>);
    const myChart = echarts.init(document.getElementById('third'));
    if (!myChart) {
      return;
    }
    // 指定图表的配置项和数据
    let base = +new Date(1968, 9, 3);
    let oneDay = 24 * 3600 * 500;
    const date = [];
    const yData1 = [Math.random() * 300];
    for (let i = 1; i < state.maxNum; i++) {
      var now = new Date((base += oneDay));
      date.push([now.getFullYear(), now.getMonth() + 1, now.getDate()].join('/'));
      yData1.push(Math.round((Math.random() - 0.5) * 20 + yData1[i - 1]));
    }
    const option = {
      toolbox: {
        show: true,
        feature: {
          dataZoom: {
            yAxisIndex: 'none',
          },
          dataView: {
            readOnly: false,
          },
          magicType: {
            type: ['line', 'bar'],
          },
          restore: {},
          saveAsImage: {},
        },
      },
      legend: {},
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true,
      },
      xAxis: [
        {
          type: 'category',
          boundaryGap: false,
          data: date,
        },
      ],
      yAxis: [
        {
          type: 'value',
        },
      ],
      series: [
        {
          name: 'Direct',
          type: 'bar',
          data: yData1,
        },
      ],
    };
    console.log('option', option);
    myChart.setOption(option, true);
    // dom.setOption(option, true);
    state.barChart2 = myChart;
  }

  function renderLineChart2(val: any): any {
    // const { setOptions } = useECharts(chartLineRef1 as Ref<HTMLDivElement>);
    const myChart = echarts.init(document.getElementById('second'));
    if (!myChart) {
      return;
    }
    let base = +new Date(1968, 9, 3);
    let oneDay = 24 * 3600 * 500;
    const date = [];
    const yData1 = [Math.random() * 300];
    const yData2 = [Math.random() * 100];
    for (let i = 1; i < state.maxNum; i++) {
      var now = new Date((base += oneDay));
      date.push([now.getFullYear(), now.getMonth() + 1, now.getDate()].join('/'));
      yData1.push(Math.round((Math.random() - 0.5) * 20 + yData1[i - 1]));
      yData2.push(Math.round((Math.random() - 0.5) * 20 + yData2[i - 1]));
    }
    const option = {
      title: {
        text: 'line',
      },
      tooltip: {
        trigger: 'axis',
      },
      legend: {},
      toolbox: {
        show: true,
        feature: {
          dataZoom: {
            yAxisIndex: 'none',
          },
          dataView: {
            readOnly: false,
          },
          magicType: {
            type: ['line', 'bar'],
          },
          restore: {},
          saveAsImage: {},
        },
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: date,
      },
      yAxis: {
        type: 'value',
        axisLabel: {
          formatter: '{value} °C',
        },
      },
      series: [
        {
          name: 'Highest',
          type: 'line',
          data: yData1,
          markPoint: {
            data: [
              {
                type: 'max',
                name: 'Max',
              },
              {
                type: 'min',
                name: 'Min',
              },
            ],
          },
          markLine: {
            data: [
              {
                type: 'average',
                name: 'Avg',
              },
            ],
          },
        },
        {
          name: 'Lowest',
          type: 'line',
          data: yData2,
          markPoint: {
            data: [
              {
                name: '周最低',
                value: -2,
                xAxis: 1,
                yAxis: -1.5,
              },
            ],
          },
          markLine: {
            data: [
              {
                type: 'average',
                name: 'Avg',
              },
              [
                {
                  symbol: 'none',
                  x: '90%',
                  yAxis: 'max',
                },
                {
                  symbol: 'circle',
                  label: {
                    position: 'start',
                    formatter: 'Max',
                  },
                  type: 'max',
                  name: '最高点',
                },
              ],
            ],
          },
        },
      ],
    };
    console.log('option', option);
    myChart.setOption(option, true);
    // dom.setOption(option, true);
    state.barChart1 = myChart;
  }

  function renderLineChart1(val: any): any {
    // const { setOptions } = useECharts(chartLineRef1 as Ref<HTMLDivElement>);
    const myChart = echarts.init(document.getElementById('first'));
    if (!myChart) {
      return;
    }
    // 指定图表的配置项和数据
    let base = +new Date(1968, 9, 3);
    let oneDay = 24 * 3600 * 500;
    let date = [];
    let data = [Math.random() * 300];
    for (let i = 1; i < state.maxNum; i++) {
      var now = new Date((base += oneDay));
      date.push([now.getFullYear(), now.getMonth() + 1, now.getDate()].join('/'));
      data.push(Math.round((Math.random() - 0.5) * 20 + data[i - 1]));
    }
    const option = {
      tooltip: {
        trigger: 'axis',
        position: function (pt) {
          return [pt[0], '10%'];
        },
      },
      title: {
        left: 'center',
        text: 'Large Area Chart',
      },
      toolbox: {
        feature: {
          dataZoom: {
            yAxisIndex: 'none',
          },
          restore: {},
          saveAsImage: {},
        },
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: date,
      },
      yAxis: {
        type: 'value',
        boundaryGap: [0, '100%'],
      },
      dataZoom: [
        {
          type: 'inside',
          start: 0,
          end: 10,
        },
        {
          start: 0,
          end: 10,
        },
      ],
      series: [
        {
          name: 'Fake Data',
          type: 'bar',
          symbol: 'none',
          sampling: 'lttb',
          itemStyle: {
            color: 'rgb(255, 70, 131)',
          },
          data: data,
        },
      ],
    };
    console.log('option', option);
    myChart.setOption(option, true);
    state.lineChart1 = myChart;
    asyncZoom();
  }
  onMounted(() => {
    renderLineChart4();
    renderLineChart3();
    renderLineChart2();
    renderLineChart1();
  });
</script>

效果
vue2、vue3分别配置echarts多图表的同步缩放

⭐结束

本文分享结束, 💖 感谢你的阅读💖
如有不足或者错误欢迎指出!
vue2、vue3分别配置echarts多图表的同步缩放文章来源地址https://www.toymoban.com/news/detail-486221.html

到了这里,关于vue2、vue3分别配置echarts多图表的同步缩放的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • Vue3项目中使用ECharts图表并实现自适应效果

    在项目中输入如下代码: 安装完成可以在package.json中看到: 创建ECharts图表的文件barCharts.vue,将它引入并在父组件中使用。在使用setup时,我们把组件直接引入进来,就可以直接使用了,不用像Vue2那样需要注册了。 在父组件中创建一个有宽高的容器,里面放ECharts组件,ECh

    2024年02月03日
    浏览(43)
  • 解决vue3集成echarts数据刷新后图表不刷新问题

    vue3 集成 echarts 最大的坑就是出现了,reactive 的数据 刷新了,但图表缺不会刷新,查了很多资料,试了很多方式都没效果,最后测试出来解决方法很简单: 核心代码: 附上 TSX 整个页面参考

    2024年02月13日
    浏览(43)
  • vue2与vue3—引入echarts以及使用

    npm install echarts --save       main.js中   vue组件中 引入方法一: 通过getCurrentInstance main.js文件中: vue组件中: 引入方法二: 组件中直接引入

    2024年02月16日
    浏览(31)
  • uniapp导入echarts类库 开发图表类小程序vue3+ts+vite

    微信小程序和抖音小程序等都支持: 使用步骤如下 第一步:下载插件包 下载echarts插件包,并导入到项目中,然后使用插件中的组件创建容器,并导入数据就可以了。 echarts插件包地址:echarts - DCloud 插件市场 如果你是使用hbuilder写的,可以直接导入,如果你是vscode写的,就

    2024年01月21日
    浏览(36)
  • vue2与vue3项目中,分别使用element组件的message消息提示只出现一次的实现

    比如出现以上现象,想要让上一次提示没有结束,下一次提示不会出现就可以用以下方法解决 解决后的现象一:上一次提示框显示后,提示框出现的提示时间没有结束,再次点击,提示框不会有反应,在该提示的时间内一只显示,下一次提示不会出现,直到该提示的时间过了

    2024年02月02日
    浏览(30)
  • uniapp+vue3+ts+vite+echarts开发图表类小程序,将echarts导入项目使用的详细步骤,耗时一天终于弄好了

    想在uniapp和vue3环境中使用echarts是一件相当前卫的事情,官方适配的还不是很好,echarts的使用插件写的是有些不太清晰的,这里我花费了一天的时间,终于将这个使用步骤搞清楚了,并且建了一个仓库,大家可以直接clone下来使用。先看一下pc端和小程序端的效果: 微信小程

    2024年02月05日
    浏览(56)
  • Echarts图表设置x轴y轴均随滚轮滚动缩+放 区域缩放

    dataZoom 组件 用于区域缩放,从而能自由关注细节的数据信息,或者概览数据整体,或者去除离群点的影响。 type: \\\'inside\\\' : 内置型数据区域缩放组件 start: 0, :数据窗口范围的起始百分比。范围是:0 ~ 100。表示 0% ~ 100%。 end: 100, 数据窗口范围的结束百分比。范围是:0 ~ 100。

    2024年02月09日
    浏览(31)
  • echarts部分图表自带鼠标滚轮滑动整体缩放效果与拖拽整体移动效果,如何取消?

    部分echarts图表在可视区域自带鼠标滚轮缩放和拖拽移动效果。这个效果在部分场景中是多余的, 怎么将其效果取消呢? roam:true(可拖动,可缩放);false(不可拖动,不可缩放) dome Tips 实现满足上诉需求的属性即 roam。 部分echarts图表类型 不存在roam属性,即该类型图表不支

    2024年02月04日
    浏览(37)
  • echarts地图组件-地图纹理、地图3D投影、多个geo缩放同步

    1.实现效果: 2.实现代码: ①geo:{ // geo设置,outShadow为是否开启3D阴影;若开启,则layoutCenter要设置大一点偏移造成底部外框阴影效果,areaColor是区块的颜色,shadowColor是阴影的颜色 { map: \\\"jiangxi\\\", layoutCenter: this.option.outShadow ? [\\\"50%\\\", \\\"51.5%\\\"] : [\\\"50%\\\", \\\"50%\\\"], //地图位置 layoutSize: \\\"11

    2024年02月04日
    浏览(29)
  • vue3关于Echarts的简单使用及配置

    前言: ECharts,一个使用 JavaScript 实现的开源 可视化库 ,可以流畅的运行在 PC 和移动设备上,兼容当前绝大部分浏览器(IE9/10/11,Chrome,Firefox,Safari等),底层依赖矢量图形库 ZRender,提供直观,交互丰富,可高度个性化定制的数据可视化图表。 (1)安装echarts包 (2)安装

    2024年02月07日
    浏览(27)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包