【问题标题】:Integrate Blazor with Chart.js: how to pass an object将 Blazor 与 Chart.js 集成:如何传递对象
【发布时间】:2021-11-21 17:06:18
【问题描述】:

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

所以,在一天没有结果之后,我决定开始我自己的组件。我按照我在blog 中找到的说明进行操作。基本上,我的 Razor 组件名为 Chart.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 替换为例如一个类。在这个类中,我想收集所有配置,如TypeOptionsDataLabels 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.js blazor blazor-webassembly


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-09-24
      • 2019-04-02
      • 2014-11-05
      • 1970-01-01
      相关资源
      最近更新 更多