首页 > 解决方案 > 使用highcharts-vue时如何重排HighCharts?

问题描述

我有一个非常简单的组件:

<template>
    <div>
        <chart
            v-if="!loading"
            ref="priceGraph"
            constructor-type="stockChart"
            :options="chartData"
            :deepCopyOnUpdate="false"
        />
        <div v-else>Loading...</div>
    </div>
</template>

<script lang="ts">
import { Vue, Component, Prop } from "vue-property-decorator";
import { EventBus } from "../events";
import { Chart } from "highcharts-vue";
import { PriceData } from "src/models/DataFile";

@Component({
    components: { Chart }
})
export default class PriceChart extends Vue {
    @Prop({ type: Boolean, required: true })
    readonly loading!: boolean;

    @Prop({ type: Array, required: true })
    readonly prices!: PriceData;

    mounted() {
        EventBus.$on("reflow", () => {
            // NOT RIGHT:
            this.$refs.priceGraph.chart.reflow();
        });
    }

    get chartData() {
        return {
            xAxis: {},
            yAxis: {},
            series: [
                {
                    type: "candlestick",
                    data: this.prices
                }
            ]
        };
    }
}
</script>

根据highcharts-vue 文档,应该可以访问底层的 Highcharts 实例,以便我可以调用该reflow方法。但是我很难弄清楚如何...

您可以在必要时(例如,当需要获取一些数据或使用任何 Chart.prototype 函数时)通过调用特定的 Vue 组件实例图表字段来访问图表对象实例,但不支持使用其内置更新图表函数,因为这可能会导致您的应用程序和图表本身之间的数据同步出现问题(它扰乱了使用包装器的概念)。最推荐的实现方式是以演示应用程序中呈现的方式使用它。

不是 100% 清楚“调用特定的 Vue 组件实例图表字段”是什么意思,但我认为这意味着我可以说this.$refs.priceGraph.chart获取实例(Vue 组件实例的“图表”字段,我的理解是this.$refs.priceGraph应该参考到 Vue 组件实例)

但它以两种不同的方式失败。在编译时,我从 TypeScript 收到以下错误:

ERROR in /home/stevenbarnett/Repos/stockgraph/src/components/PriceChart.vue(33,26):
TS2339: Property 'chart' does not exist on type 'Element | Element[] | Vue | Vue[]'.
  Property 'chart' does not exist on type 'Element'.
Version: typescript 3.9.5

如果我忽略此错误并运行我的代码,它会在控制台中失败this.$refs.priceGraph is undefined(尽管 Vue 开发工具显示它已填充)。见附件:

在此处输入图像描述

我究竟做错了什么?

标签: javascripttypescriptvue.jshighchartsvuejs2

解决方案


你需要使用:

this.$nextTick(() => {
  this.$refs.priceGraph.chart.reflow();
});

这可以确保您引用的图表被渲染。


推荐阅读