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

Vue实例已挂载警告,Blazor跳转回页面时Vue内容不显示如何解决?

修复方案

问题原因

当前代码全局仅初始化了一次Vue应用实例,Blazor单页应用切换路由时,/dashboard/page1页面的DOM元素会被销毁,但Vue实例不会自动销毁,再次回到页面时尝试重复挂载同一个已挂载的Vue实例,就会触发警告且无法正常渲染。

1. 调整前端JS逻辑

按照Vue报错提示的工厂函数方案改造,同时增加实例卸载逻辑:

// main.js
// 抽离Vue实例创建逻辑为工厂函数
const createMyApp = () => {
  const app = createApp(App)
  app.provide('$axios', axios)
  return app
}

// 全局存储当前激活的Vue实例
let currentVueApp = null

window.renderSomething = function() {
  // 挂载前先清理之前的实例,避免冲突
  if (currentVueApp) {
    currentVueApp.unmount()
  }
  // 创建新实例挂载
  currentVueApp = createMyApp()
  currentVueApp.mount('#ticker-maintenance-host')
}

// 暴露卸载方法供Blazor侧调用
window.unmountVueApp = function() {
  if (currentVueApp) {
    currentVueApp.unmount()
    currentVueApp = null
  }
}

2. 调整Blazor侧逻辑

监听组件销毁生命周期,主动清理Vue实例,避免内存泄漏:

@inject IJSRuntime JS
@implements IAsyncDisposable

@page "/dashboard/page1"

<div id="ticker-maintenance-host"></div>

@code{
    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            await JS.InvokeVoidAsync("renderSomething");
        }
    }

    // 组件销毁时主动卸载Vue实例
    public async ValueTask DisposeAsync()
    {
        await JS.InvokeVoidAsync("unmountVueApp");
    }
}

可选优化

如果你的Blazor路由配置会复用页面组件(切走再回来不会触发firstRender),可以去掉if (firstRender)判断,每次OnAfterRenderAsync都调用renderSomething即可,JS侧已经做了实例去重处理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 16:15:05