You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Blazor SSR(无交互):OnInitializedAsync执行时如何显示加载提示?

在无交互Blazor SSR中结合BlazorPageScript实现OnInitializedAsync加载提示

1. 组件中添加加载提示元素

在你的Blazor SSR组件(.razor文件)里,先添加默认显示的加载提示,初始状态设为可见:

<div id="loading-indicator" class="loading">加载中...</div>

@* 组件实际内容区域,初始为空 *@
<div>@LoadedContent</div>

搭配基础样式(可放在组件<style>标签或全局样式文件):

.loading {
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    font-size: 1.2rem;
    color: #333;
    z-index: 9999;
}

2. 组件逻辑中触发状态更新

注入BlazorPageScript,重写OnInitializedAsync,完成异步操作后通知前端更新状态:

@inject BlazorPageScript.PageScript PageScript

@code {
    private string LoadedContent { get; set; } = string.Empty;

    protected override async Task OnInitializedAsync()
    {
        // 模拟异步加载(如API请求、数据处理)
        await Task.Delay(2000);
        LoadedContent = "加载完成,显示内容";

        // 通过BlazorPageScript调用JS更新函数
        await PageScript.InvokeAsync("onUpdate", new { isLoaded = true });
    }
}

3. 编写对应JavaScript函数

在页面脚本(如_Host.cshtml或组件关联脚本)中实现onLoad和onUpdate:

// Blazor初始化完成时触发
function onLoad() {
    // SSR已渲染加载提示,此处可做额外初始化逻辑
}

// 接收Blazor发送的加载状态更新
function onUpdate(data) {
    if (data.isLoaded) {
        const loadingEl = document.getElementById('loading-indicator');
        if (loadingEl) loadingEl.style.display = 'none';
    }
}

核心说明

  • SSR特性保证加载提示在页面打开时直接显示,无需等待Blazor客户端初始化
  • OnInitializedAsync完成后,通过BlazorPageScript的InvokeAsync触发JS隐藏提示
  • 确保已正确配置BlazorPageScript(如在Program.cs中添加builder.Services.AddBlazorPageScript())

内容的提问来源于stack exchange,提问作者SteveGundeck

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 13:38:16