chart.js - 将 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);
。
解决方案
好的,这很容易。我看到了很多不同的技术,但是有一个非常基本的简单方法
await JSRuntime.InvokeVoidAsync("setup", Config.CanvasId, Config);
推荐阅读
- scylla - scylladb:scylla_io_setup 脚本未在输出中显示推荐的 --max-io-requests 参数
- javascript - 通过单击按钮角度材料更改选项卡我收到错误
- azure - 如何从 WebPart 获取 Sharepoint 的访问令牌?
- gulp - Babel 导出聚合时抛出类型错误
- python - 对多个熊猫数据框执行相同操作的正确方法是什么?
- perl - 每行的水平绝对值
- java - Java Scanner.nextLine() 错误地将 unicode (emoji) 解析为新行
- python-3.x - 从字符串中删除多个相似词 - Python
- excel - 从多个 excel 文件中读取数据并在另一个 excel 中使用它进行一些计算
- gatling - 我想从场景中获取值并在 QueryParam 中设置值