Vue.js 3组合式API中进入/重载SPA时如何卸载应用?
Vue 3 应用实例重复挂载警告的解决方案
问题描述
浏览器控制台出现如下警告:
[Vue warn]: There is already an app instance mounted on the host container.
If you want to mount another app on the same host container, you need to unmount the
previous app by callingapp.unmount()first.
我在正确调用app.unmount()时遇到了问题,相关代码如下:
main.js
// Import methods and component. import { createApp} from 'vue'; import router from './router'; import App from './App.vue'; // Create vue App. const app = createApp(App); // Install the required instances like plugin, component and directive. app.use(router); // Mount 'app' const (App.vue) as root component. app.mount('#app');
App.vue
<template> <div> <div id="header">Hello world</div> <div id="main"> <router-view name="default" v-slot="{ Component, route }"> <div v-if="errMsg" class="container mt-3"> <h2 class="text-center"> {{ errMsg }} </h2> </div> <div v-else> <component :is="Component" :key="route.meta.usePathKey ? route.path : undefined"> </component> </div> </router-view> </div> </div> </template> <script> import {ref, onErrorCaptured} from 'vue'; export default { name: "App", } </script> <script setup> // constants, functions and life-cycle hooks const errMsg = ref(null); onErrorCaptured(() => { errMsg.value = "Something went wrong!"; }); </script> <style> </style>
注意事项
- 无法直接在main.js中使用
app.unmount(); - 无法使用onUnmounted等Vue生命周期钩子(仅能在setup()脚本内使用);
- 无法从App.vue中卸载app(无意义)。
解决方案
1. 全局缓存实例,挂载前检查卸载
修改main.js,将应用实例挂载到全局对象,每次初始化前先检查并卸载旧实例:
import { createApp} from 'vue'; import router from './router'; import App from './App.vue'; // 检查全局缓存的旧实例,存在则卸载 if (window.__VUE_APP_INSTANCE__) { window.__VUE_APP_INSTANCE__.unmount(); } const app = createApp(App); app.use(router); // 将新实例缓存到全局 window.__VUE_APP_INSTANCE__ = app.mount('#app');
2. 可选:清理容器残留DOM
如果卸载后挂载容器内仍有残留DOM,可以在卸载后清空容器:
if (window.__VUE_APP_INSTANCE__) { window.__VUE_APP_INSTANCE__.unmount(); // 清空挂载容器的内容 document.getElementById('app').innerHTML = ''; }
3. 开发环境热重载适配
如果是热重载触发的重复挂载,上述全局缓存方法已能覆盖场景,无需额外配置。
内容的提问来源于stack exchange,提问作者Wadhah Sky
相关产品推荐
相关产品推荐

