Blazor WASM路由切换后Lottie Player动画不更新问题求助
解决Blazor路由切换时Lottie动画不更新的问题
问题根源在于:Blazor更新DOM属性后,lottie-player这类Web Component不会自动检测src属性变化并重新加载动画,必须手动调用它的官方API来触发重新加载。
解决方案步骤:
- 添加元素引用:给
lottie-player标签加@ref,方便后续通过JS操作该元素 - 监听参数变化:在
OnParametersSetAsync生命周期方法中,检测路由参数animNumber变化,调用JS重新加载动画 - 编写JS辅助逻辑:调用
lottie-player的load()方法重新加载新的动画资源
修改后的完整代码:
@page "/{animNumber:int}" @inject IJSRuntime JSRuntime @inject NavigationManager navigationManager <PageTitle>Index</PageTitle> <h3>Anim @animNumber</h3> <lottie-player @ref="lottiePlayer" src="lottie/@(animNumber).json" background="transparent" speed="1" style="width: 300px; height: 300px;" loop autoplay></lottie-player> <audio id="roar" src="/sound/duo.mp3" @onended="NavigateToNextAnimation" /> <button id="soundButton" @onclick="PlaySound">Click me!</button> @code { [Parameter] public int animNumber { get; set; } private ElementReference lottiePlayer; private int _previousAnimNumber; protected override async Task OnParametersSetAsync() { // 仅当参数变化时才重新加载动画 if (animNumber != _previousAnimNumber) { // 更新lottie-player的src并重新加载 await JSRuntime.InvokeVoidAsync("updateLottieAnimation", lottiePlayer, $"lottie/{animNumber}.json"); _previousAnimNumber = animNumber; } await base.OnParametersSetAsync(); } public async Task PlaySound() { await JSRuntime.InvokeAsync<string>("PlayAudio", "roar"); animNumber++; } public void NavigateToNextAnimation() { navigationManager.NavigateTo($"/{animNumber}"); } }
添加JS辅助函数
在你的wwwroot/js目录下创建lottie-utils.js文件,内容如下:
window.updateLottieAnimation = async (element, src) => { element.src = src; // 调用lottie-player的load方法重新加载动画 await element.load(); } window.PlayAudio = (id) => { const audio = document.getElementById(id); audio.play(); }
然后在_Host.cshtml(Server项目)或index.html(WASM项目)中引入该JS文件:
<script src="js/lottie-utils.js"></script> <!-- 确保先引入lottie-player的官方脚本 --> <script src="https://unpkg.com/@lottiefiles/lottie-player@latest/dist/lottie-player.js"></script>
原方案无效的原因
Blazor的组件更新机制只会修改DOM属性,但lottie-player作为自定义元素,需要显式调用它的load()方法才能重新读取src并加载新动画。单纯修改src属性不会触发内部的资源重新加载逻辑,这是Web Component的特性,并非Blazor的问题。
内容的提问来源于stack exchange,提问作者Laftek
相关产品推荐
相关产品推荐

