解决vue-echarts的dataZoom在更新后丢失已选位置的问题 | How to solve dataZoom of vue-echarts loses the selected position after updating options

vue-echarts在启用了dataZoom后如果options被更新,dataZoom的start和from会被重置。解决这个问题可以采用下面的方法。

假设你之前是这么配置组件的

<e-charts
  :options="options"
  v-if="options"
  class="chart"
  autoresize
></e-charts>

首先,在组件上监听dataZoom事件

<e-charts
  :options="options"
  class="chart"
  @datazoom="dataZoom"
  autoresize
></e-charts>

在data中添加zoomStart和zoomEnd

dataZoom(action) {
  if (
    "batch" in action &&
    Array.isArray(action.batch) &&
    action.batch.length > 0
  ) {
    this.zoomStart = action.batch[0].start;
    this.zoomEnd = action.batch[0].end;
  } else if ("start" in action && "end" in action) {
    this.zoomStart = action.start;
    this.zoomEnd = action.end;
  }
}

dataZoom事件有两种触发方式,第一个if分支将在使用滚轮时触发,第二个分支将在拖动手柄时触发。

在data中添加realOptions。然后,在watch下面监听options的变化,将zoomStart和zoomEnd重新赋值。

options(newValue) {
  if (newValue) {
    for (let i = 0; i < newValue.dataZoom.length; i++) {
      newValue.dataZoom[i].start = this.zoomStart;
      newValue.dataZoom[i].end = this.zoomEnd;
    }
    this.realOptions = newValue;
  }
}

最后,修改组件的属性

<e-charts
  :options="realOptions"
  v-if="realOptions"
  class="chart"
  @datazoom="dataZoom"
  autoresize
></e-charts>

 


If the options are updated after dataZoom has enabled in vue-echarts, the start and from of dataZoom will be reset. The following methods can be used to solve this problem.

Suppose your component looks like this

<e-charts
  :options="options"
  v-if="options"
  class="chart"
  autoresize
></e-charts>

First, listen to the dataZoom event on the component

<e-charts
  :options="options"
  class="chart"
  @datazoom="dataZoom"
  autoresize
></e-charts>

Create zoomStart and zoomEnd fields to data.

dataZoom(action) {
  if (
    "batch" in action &&
    Array.isArray(action.batch) &&
    action.batch.length > 0
  ) {
    this.zoomStart = action.batch[0].start;
    this.zoomEnd = action.batch[0].end;
  } else if ("start" in action && "end" in action) {
    this.zoomStart = action.start;
    this.zoomEnd = action.end;
  }
}

There are two ways to trigger the dataZoom event. The first if branch will be triggered when the scroll wheel is used, and the second branch will be triggered when the handle is dragged.

Create a realOptions field to data. Then, watch the changes of options and assign zoomStart and zoomEnd.

options(newValue) {
  if (newValue) {
    for (let i = 0; i < newValue.dataZoom.length; i++) {
      newValue.dataZoom[i].start = this.zoomStart;
      newValue.dataZoom[i].end = this.zoomEnd;
    }
    this.realOptions = newValue;
  }
}

Finally, modify the properties of your component

<e-charts
  :options="realOptions"
  v-if="realOptions"
  class="chart"
  @datazoom="dataZoom"
  autoresize
></e-charts>

 

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注