javascript - 路线更改时,绘制箱线图无法正确重新布局
问题描述
我在 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
并设置responsive
为true
有没有一种方法可以使绘图已经具有适当的大小(高度和宽度)而无需将鼠标悬停在它上面?这是可以清楚地看到此行为的复制示例:
https://codesandbox.io/s/vuetify-with-plotly-20nev
任何一种重新布局都会破坏情节的布局,只有在悬停之后,它才会变得正确。
还有一件事是我不能为 Plotly 使用 Vue 包装器(它还有其他问题),所以我必须坚持plotly.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()
},
}
推荐阅读
- java - 如何在 Junit 中使用 assertEquals 解决这个问题?
- windows - 在 Windows 上的 Meson 构建中链接到现有的`.lib` 文件
- python - 如何使异步任务/协程返回值被分配
- javascript - 仅推送最近输入值的函数
- variables - 在内部调用时将变量从一个 mixin 传递到另一个 mixin
- regex - 使用正则表达式识别模式并清理 pandas 列中的数据
- python - Pandas groupby 只有正值的平均值
- git - 在 GitHub 上更改作者信息后应该执行哪些本地操作?
- ios - 使用新的数组值立即更新前端
- python - 想要一个整数,得到元组?