我有一个Blazor服务器应用程序,在那里我使用chart.js库创建了一个饼图。
“Chart.JS错误:Microsoft.JSInterop.JSException:找不到'setup'('setup'未定义)”
我在谷歌上搜索了很多,我想也许安装程序在定义之前就被调用了。它是在我添加的项目中的“chart.js”中定义的。我不知道我是否在_host.cshtml中没有正确地调用它,或者在我的项目中没有正确地放置它。
这里我的代码:
_Host.cshtml(body部分的相关部分。我在给定路径中有所有的js文件。第一行chart.js在我的项目中,我在那里定义了window.setup)
<script src="chart.js"></script>
<script src="files/js/chart.js"></script>
<script src="files/js/chart.min.js"></script>
<script src="files/js/bootstrap.min.js"></script>
<script src="files/js/helpers.esm.js"></script>
<script src="files/js/jquery.slim.min.js"></script>
<script src="files/js/popper.min.js"></script>
<script src="files/js/helpers.mjs"></script>
<script src="files/js/chart.mjs"></script>
项目中的chart.js
window.setup = (id, config) => {
var ctx = document.getElementById(id).getContext('2d');
new Chart(ctx, config);
}
图表所在的剃刀页
@page "/wmi_performance2"
@inject TagService TagService
@using System.IO
@inject IJSRuntime JSRuntime
<Chart Id="pie1" Type="@Chart.ChartType.Pie"
Data="@(new[] { "1", "2" })" BackgroundColor="@(new[] { "blue","green" })"
Labels="@(new[] { "Fail","Ok" })">
</Chart>
Shared/Components文件夹中的My Chart.razor(在调用方法设置时,我在这里得到了错误)
@using System.IO
@inject IJSRuntime JSRuntime
@using Microsoft.JSInterop;
@inject IJSRuntime jsInvoker
<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
try{
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);
}
catch(Exception e)
{
using (StreamWriter sw = File.AppendText((Pages.CommonClass.error_path)))
{
sw.WriteLine("Chart.JS Error: " + e + Environment.NewLine);
}
}
}
}
1条答案
按热度按时间iyfjxgzm1#
我已经创建了一个chartiderjs文件,安装程序直接在wwwroot下。然后它就工作了。