[Vuejs]-Single Page Application: How to unmount app in Vue.js 3 Composition API when enter/reload the app?

0👍

The solution, I should see if app (App.vue) is already mount, it’s useful:

1- When refresh the page, so you don’t need to mount another app instance as Webpack server suggest in the warning.

2- Will prevent trigger the methods these defined in App.vue <script setup> twice (one for update life-cycle of component and second when re-mount the component again, which happens when refresh the page).

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);
}

If you don’t want to use the existing app instance, you can change the code by use app.unmount() inside if{} block and remove else{} block, then outside the condition block plug in your components, stores..etc to the new created app instance and mount it at the end.

Leave a comment