首页 > 解决方案 > 路线更改时,绘制箱线图无法正确重新布局

问题描述

我在 Vue 中使用 Plotly,当我访问新路线时,绘图没有正确呈现。只有在悬停后,绘图才会更改为适当的大小。当我更改为具有不同网格的另一条路线(对于相同的绘图 UUID)时,绘图似乎有某种错误的大小,并且溢出了容器。但是,如果我将鼠标悬停在它上面,那似乎还不错。这是我用于绘图和重新布局的代码:

  mounted() {
    Plotly.plot(
      this.$refs[this.chartCopy.uuid],
      this.chartCopy.traces,
      this.chartCopy.layout
    );
    this.$refs[this.chartCopy.uuid].on("plotly_hover", this.hover);
    this.$refs[this.chartCopy.uuid].on("plotly_unhover", this.unhover);
  },
  watch: {
    chart: {
      handler: function () {
        Plotly.react(
          this.$refs[this.chartCopy.uuid],
          this.chartCopy.traces,
          this.chartCopy.layout
        );
      },
      deep: true,
    },
  },

在选项和布局中,我设置autosize并设置responsivetrue 有没有一种方法可以使绘图已经具有适当的大小(高度和宽度)而无需将鼠标悬停在它上面?这是可以清楚地看到此行为的复制示例:

https://codesandbox.io/s/vuetify-with-plotly-20nev

任何一种重新布局都会破坏情节的布局,只有在悬停之后,它才会变得正确。

还有一件事是我不能为 Plotly 使用 Vue 包装器(它还有其他问题),所以我必须坚持plotly.js只使用库。

标签: javascriptvue.jsplotlyplotly.js

解决方案


响应式图表

要使图表响应窗口大小,请设置选项的responsive属性config第四个参数Plotly.plot()

// Boxplot.vue
export default {
  mounted() {
    Plotly.plot(
      this.$refs[this.chartCopy.uuid],
      this.chartCopy.traces,
      this.chartCopy.layout,
      { responsive: true } 
    )
  }
}

重新布局

要执行图表的重新布局,请使用IntersectionObsesrver调用Plotly.relayout(). 这应该在钩子中设置并在mounted钩子中拆除beforeDestroy

// Boxplot.vue
export default {
  mounted() {
    const chart = this.$refs[this.chartCopy.uuid]
    const intersectionObserver = new IntersectionObserver(entries => {
      entries.forEach(entry => {
        if (entry.isIntersecting) {
          requestIdleCallback(() => Plotly.relayout(entry.target, {}))
        }
      })
    })
    intersectionObserver.observe(chart)
    this._unobserveChart = () => intersectionObserver.unobserve(chart)
  },
  beforeDestroy() {
    this._unobserveChart()
  },
}

使用 Plotly 编辑 Vuetify(分叉)


推荐阅读