Blazor 服务器应用程序中的加载进度通常是通过SignalR连接实现的。当页面加载时,一个JavaScript函数会被调用以启动SignalR连接,该连接将负责与服务器通信,并从服务器接收更新,以显示加载进度。
以下是采用C# 和 Razor语言的示例代码:
@page "/"
Loading ...
@code {
protected override async Task OnInitializedAsync()
{
var hubConnection = new HubConnectionBuilder()
.WithUrl(NavigationManager.ToAbsoluteUri("/hub"))
.Build();
hubConnection.On("UpdateProgress", (progress) =>
{
// Update the UI with the current progress
Console.WriteLine(progress);
});
await hubConnection.StartAsync();
}
}
从示例中可以看出,代码使用了一个SignalR连接, 并在连接启动后,定义了一个名为“UpdateProgress”的回调方法, 用以在UI上更新加载进度。需要注意的是,这里的连接路径/hub
与服务端中的MapHub
方法的第一个参数保持一致:
app.UseEndpoints(endpoints =>
{
endpoints.MapBlazorHub();
endpoints.MapHub("/hub");
endpoints.MapFallbackToPage("/_Host");
});
除了使用SignalR外,还可以结合JavaScript和CSS来实现加载进度条效果。这种解决方法可以通过从一个页面转移到另一个页面时重新启动浏览器的渲染机制来工作,并使用了jQuery库和CSS样式。处理逻辑如下:
@page "/"
@functions {
private string JsInteropFunction = @"
window.interop = {
startProgressBar: function ( ) {
$('#loading-bar').show();
},
updateProgressBar: function ( percent ) {
$('#loading-bar').css('width', percent + '%');