首页 > 解决方案 > 将 Blazor 与 Chart.js 集成:如何传递对象

问题描述

我想在我的 Blazor WebAssembly 应用程序中显示一些带有Chart.js. 我尝试使用Chartjs.Blazor.Fork,但几乎没有错误,例如我打开了另一篇关于here的帖子。

所以,在一天没有结果之后,我决定开始我自己的组件。我按照我在博客中找到的说明进行操作。基本上,我Chart.razor使用以下代码调用了我的 Razor 组件

@inject IJSRuntime JSRuntime

<canvas id="@Id"></canvas>

@code {
    public enum ChartType
    {
        Pie,
        Bar
    }

    [Parameter]
    public string Id { get; set; }

    [Parameter]
    public ChartType Type { get; set; }

    [Parameter]
    public string[] Data { get; set; }

    [Parameter]
    public string[] BackgroundColor { get; set; }

    [Parameter]
    public string[] Labels { get; set; }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        // Here we create an anonymous type with all the options
        // that need to be sent to Chart.js
        var config = new
        {
            Type = Type.ToString().ToLower(),
            Options = new
            {
                Responsive = true,
                Scales = new
                {
                    YAxes = new[]
                    {
                        new { Ticks = new {
                            BeginAtZero=true
                        } }
                    }
                }
            },
            Data = new
            {
                Datasets = new[]
                {
                    new { Data = Data, BackgroundColor = BackgroundColor}
                },
                Labels = Labels
            }
        };

        await JSRuntime.InvokeVoidAsync("setup", Id, config);
    }
}

然后我有自己的mychart.js脚本来更新图表

window.setup = (id,config) => {
    var ctx = document.getElementById(id).getContext('2d');
    new Chart(ctx, config);
}

所以,我使用这段代码

<Chart Id="bar1" Type="@Chart.ChartType.Bar"
       Data="@(new[] { " 10", "9" } )"
       BackgroundColor="@(new[] { " yellow","red"} )"
       Labels="@(new[] { " Fail","Ok" } )">
</Chart>

丑陋的代码,但它正在工作。现在,我可以在我的页面中显示一个图表。凉爽的!我想要显示的是更复杂的东西,因为我必须显示一个带有组的堆叠条形图,并且配置非常复杂。

我想config用例如一个类替换你可以在页面中看到的。在这个类中,我想收集所有配置,比如Type, Options, Data, Labels and so on, and pass them in the await JSRuntime.InvokeVoidAsync("setup", Id, config);`

首先,我创建了我的基类,例如

public abstract class ConfigBase
{
    protected ConfigBase(ChartType chartType)
    {
        Type = chartType;
    }

    public ChartType Type { get; }
    public string CanvasId { get; } = Guid.NewGuid().ToString();
}

我的问题是如何转换此类以获得正确执行 JavaScript 的有效对象new Chart(ctx, config);

标签: chart.jsblazorblazor-webassembly

解决方案


好的,这很容易。我看到了很多不同的技术,但是有一个非常基本的简单方法

await JSRuntime.InvokeVoidAsync("setup", Config.CanvasId, Config);

推荐阅读