单页应用程序:进入/重新加载应用程序时如何在 Vue.js 3 Composition API 中卸载应用程序?

问题描述 投票:0回答:1

Webpack 服务器在浏览器控制台中显示以下警告:

[Vue warn]: 宿主容器上已经挂载了一个app实例。 如果你想在同一个主机容器上挂载另一个应用程序,你需要卸载 以前的应用程序通过调用

app.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>

注意

1-我不能在

app.unmount()
中直接使用
main.js

2- 不能像

onUnmounted()
那样使用 Vue 生命周期钩子,因为应该只在 setup() 脚本中使用。

3-无法从

app
卸载
App.vue
(废话)。

javascript vue.js webpack vuejs3 vue-router
1个回答
0
投票

解决方案,我应该看看

app
(App.vue)是否已经挂载,它很有用:

1- 刷新页面时,您不需要像 Webpack 服务器在警告中建议的那样安装另一个

app
实例。

2- 将防止触发

App.vue
<script setup>
中定义的方法两次(一次用于更新组件的生命周期,第二次用于重新安装组件,这在刷新页面时发生)。

main.js


// Import methods and component.
import { createApp} from 'vue';
import router from './router';
import App from './App.vue';


let app = "";
let containerSelector = "#app";

// check if app has been mounted already
const mountPoint = document.querySelector(containerSelector);

if (mountPoint && mountPoint.__vue_app__ !== undefined) {

    // Set the existing mount point to 'app'.
    app = mountPoint.__vue_app__._instance.proxy;
}
else {

    // create a new app instance
    app = createApp(App);
    
    // Install the required instances like plugin, component and directive.
    app.use(router);

    // Mount 'app' (App.vue) as root component.
    app.mount(containerSelector);
}

如果您不想使用现有的

app
实例,您可以通过在
app.unmount()
块内使用
if{}
来更改代码并删除
else{}
块,然后在条件块外插入您的组件,商店。 .etc 到新创建的
app
实例并在最后安装它。

© www.soinside.com 2019 - 2024. All rights reserved.