作者热门文章
- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我有一个图表,其中轴内容和数据会随时间变化。这发生在 Vue 框架中。
我的想法是使用 setData()
和 setCategories()
为图表提供指向动态数据的指针。这不起作用:当数据更新时,图表没有。
例子在Codepen.io并转载如下以供引用。请注意,这会挂起我的浏览器(但 codepen 版本没问题)
new Vue({
el: "#app",
data: {
config: {
chart: {
type: 'heatmap'
},
series: [{}]
},
src: ['a', 'b'],
dst: ['x', 'y'],
data: [[0, 0, 1], [0, 1, 2], [1, 0, 3], [1, 1, 4]],
chart: undefined
},
mounted() {
this.chart = Highcharts.chart('container', this.config)
console.log(this.chart)
// the content of the axis and the data will be dynamic
this.chart.series[0].setData(this.data, true)
this.chart.xAxis[0].setCategories(this.src, true)
this.chart.yAxis[0].setCategories(this.dst, true)
// simulation of some data changing after some time
setTimeout(() => {
this.data = [[0, 0, 10], [0, 1, 20], [1, 0, 30], [1, 1, 40]]
// console.log('updated')
}, 3000)
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highcharts/6.0.6/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/heatmap.js"></script>
<div id="app">
<div id="container">
</div>
</div>
最佳答案
要让图表自动更新,您需要使用观察器或在 View 中使用它们来观察 vue 变量。
我正在使用以下步骤:
由于 Highcharts 在工作之前需要页面上的真实元素,我们不能直接在 View 中使用它们,我们需要在可以更改的字段上使用观察器。
我们首先将图表渲染代码提取到一个单独的函数中,这允许我们从多个地方调用该方法。
然后我们为我们的图表需要的变量添加观察者,在这些观察者中,我们调用我们的渲染函数。
最后,我们在 mounted 方法中渲染我们的图表。
从这一点上,我们可以看出我们使用的库 Highcharts 还支持在更改时动态更新数据,我们可以利用这一点来防止重新渲染完整元素,并在这里节省一些 CPU 周期。
new Vue({
el: "#app",
data: {
chart: undefined,
config: {
chart: {
type: 'heatmap'
},
series: [{}]
},
src: ['a', 'b'],
dst: ['x', 'y'],
data: [[0, 0, 1], [0, 1, 2], [1, 0, 3], [1, 1, 4]]
},
mounted() {
this.render();
// simulation of some data changing after some time
setTimeout(() => {
this.data = [[0, 0, 10], [0, 1, 20], [1, 0, 30], [1, 1, 40]]
console.log('updated')
}, 3000)
},
watch: {
data() {
this.chart.series[0].setData(this.data, true)
},
config() {
this.render();
},
src() {
this.chart.xAxis[0].setCategories(this.src, true)
},
dst() {
this.chart.yAxis[0].setCategories(this.dst, true)
},
},
methods: {
render() {
this.chart = Highcharts.chart('container', this.config)
// the content of the axis and the data will be dynamic
this.chart.series[0].setData(this.data, true)
this.chart.xAxis[0].setCategories(this.src, true)
this.chart.yAxis[0].setCategories(this.dst, true)
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highcharts/6.0.6/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/heatmap.js"></script>
<div id="app">
<div id="container">
</div>
</div>
关于highcharts - 如何在 Highcharts 中使用 Vue 绑定(bind)数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48707827/
我是一名优秀的程序员,十分优秀!