【发布时间】:2020-08-13 01:32:39
【问题描述】:
当我使用来自另一个页面的链接导航到该页面时,我的 OnInitialized() 中有一项繁重的任务(获取数据),它冻结直到繁重的任务结束,如何在页面之间导航时显示一般加载动画。
【问题讨论】:
-
最大的问题当然是:为什么“繁重的任务(获取数据)”不是异步的?因为如果它可以使用异步 I/O,您将拥有一个优雅的和高效的解决方案。
当我使用来自另一个页面的链接导航到该页面时,我的 OnInitialized() 中有一项繁重的任务(获取数据),它冻结直到繁重的任务结束,如何在页面之间导航时显示一般加载动画。
【问题讨论】:
最重要的是,要防止您的页面冻结,请使用 OnInitializedAsync 方法而不是 OnInitialized。
在您的组件页面的视图部分,您可以添加如下代码来查询您的数据(人物对象列表)是否仍然不可用:
@if (people == null)
{
<p>Loading people...</p>
}
else
{
<ul class="people-list">
@foreach (var person in people)
{
<li class="people-list-item">
<a href="@person.Id">
<PersonCard Person="person" />
</a>
</li>
}
</ul>
}
只要数据不可用,就会显示消息“正在加载人员...”。当数据可用时,将显示它而不是上面的消息。您可以显示动画而不是消息,例如 MatProgressBar。您甚至可以简单地放置一个带有加载动画的 img 元素 图片代替或补充短信...
希望对你有帮助……
【讨论】:
如果您想显示/隐藏微调器或进度条,请编写这样的 Javascript 函数,我们假设您使用 NProgress(显示微调器和进度条的 javascript 插件并不重要):
window.progress = (action=> {
if (action === "start") NProgress.start();
else if (action === "stop") NProgress.done();
};
然后你可以启动和停止它:
JSRuntime.InvokeVoidAsync("progress", "start");
// do the heavy process
JSRuntime.InvokeVoidAsync("progress", "stop");
如果你想显示进度,你需要有一个 SignalR Hub,那么你的 JavaScript 是这样的:
connection.on("ReceiveProgress", function (progress) {
if (progress <= 100) NProgress.set(progress / 100);
else NProgress.done();
});
在中心:
public async static Task SetProgress(int total, int index)
{
int progress = 0;
if (total != 0) progress = Convert.ToInt32(Math.Ceiling((double)(index * 100) / (double)total));
else progress = 0;
await _hubContext.Clients.User(State.User.Current.Id).SendAsync("ReceiveProgress", progress);
}
现在在您的 Blazor 代码中增加进度:
for(int i = 1 ; i<= total; i++)
{
// do the process step by step
await Noty.SetProgress(total, i);
}
【讨论】: