【发布时间】: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 替换为例如一个类。在这个类中,我想收集所有配置,如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.js blazor blazor-webassembly