ChartJS 图表3.x:ResizeObserver不是构造函数

nzkunb0c  于 2022-11-06  发布在  Chart.js
关注(0)|答案(2)|浏览(249)

我试图在LWC中使用ChartJs,我取了最后的3.3.2版本并遵循了几个例子以便创建我的图表(here是我找到的最完整的例子之一),但在调用指令时:

this.chart = new window.Chart(ctx, config);

我收到错误消息“TypeError:ResizeObserver不是构造函数”.“
我尝试用旧版本替换ChartJs资源,发现使用2.8.0版本时,图表可以正确加载,没有任何错误。
由于从文档中指定的3.x版本引入了一些改进,所以我更喜欢使用最新的版本,而不是2.8.0。我也试图搜索一些关于ResizeObserver的信息,但我不明白它是什么,为什么我会有问题。从LWC看,我似乎没有导入任何其他东西。
有没有办法解决这个问题?

j7dteeu8

j7dteeu81#

可能是您试图在不支持ResizeObserver的浏览器/版本组合中运行它。
您可以检查此选项,并查看您的浏览器版本是否支持此功能:https://www.caniuse.com/resizeobserver
如果没有,可以使用多边形填充来添加所需的行为,例如:https://github.com/juggle/resize-observer

bakd9h0s

bakd9h0s2#

我在Chart.Js中遇到了同样的问题--但幸运的是,您可以关闭响应并实现自己的版本。
我只是在这里张贴下面:https://salesforce.stackexchange.com/questions/379134/how-to-use-loadscript-with-light-dom-in-lwc-getting-error-invariant-violation/383560#383560

createChart() {
    const element = this.querySelector('[data-id="chart"]');
    const config = deepClone(this._chartConfiguration);
    //Ensure that the responsiveness is disabled as ResizeObserver
    //is not supported by the LockerService
    if (!config.options) {
        config.options = {
            responsive: false
        };
    } else {
        config.options.responsive = false;
    }
    this.chartInstance = new Chart(
        element.getContext("2d"),
        config
    );
    this.chartInstance.resize();
}

connectedCallback() {
    try {
        window.addEventListener(
            "resize",
            this.handleWindowResize
        );
    } catch (ex) {
        //Handle this
    }
}

disconnectedCallback() {
    try {
        window.removeEventListener(
            "resize",
            this.handleWindowResize
        );
    } catch (ex) {
        //Handle this
    }
}

handleWindowResize = () => {
    if (this.chartCreated === true) {
        this.chartInstance.resize();
    }
}

Chart.Js响应文档链接:https://www.chartjs.org/docs/latest/configuration/responsive.html

相关问题