Vue3 app.unmount() Function


Vue3 全局 APIVue3 Global API

In Vue3,app.unmount()it is used to unmount (i.e., destroy) already mounted Vue application instances.

app.unmount()is a very useful function in Vue3, which allows you to safely destroy Vue application instances and release related resources.


1. What isapp.unmount()?

app.unmount()is a global API provided by Vue3, used to unmount already mounted Vue application instances. When you call this function, Vue will perform the following operations:

  • Destroy all component instances.
  • Remove all event listeners.
  • Clear all DOM elements related to the application.

Simply put,app.unmount()it will remove the entire Vue application from the page and release all related resources.


2. Why is it neededapp.unmount()?

In some scenarios, you may need to dynamically destroy a Vue application instance. For example:

  • Single Page Application (SPA): When switching between different routes, you may need to destroy the Vue application instance of the current page to avoid memory leaks.
  • Dynamically loading components: In scenarios where components are dynamically loaded and unmounted,app.unmount()it can help you safely destroy component instances that are no longer needed.
  • Test environment: In unit tests or integration tests, you may need to destroy the Vue application instance after each test to ensure the independence and accuracy of the tests.

3. How to useapp.unmount()?

Usingapp.unmount()is very simple. Here is a basic usage example:

Example

import { createApp } from 'vue';
import App from './App.vue';

// Create Vue application instance
const app = createApp(App);

// Mount Vue application
app.mount('#app');

// Unmount Vue application
app.unmount();

Code analysis:

  1. Create application instance: First, we usecreateApp()function to create a Vue application instance and pass in the root componentApp。
  2. Mount application: Then, we callapp.mount('#app')to mount the application to the#appelement on the page.
  3. Unmount application: Finally, we callapp.unmount()to unmount the application from the page.

Notes:

  • Mount point: When callingapp.mount(), the mount point specified (e.g.#app), after callingapp.unmount(), Vue will clear it.
  • Component lifecycle: Callingapp.unmount()will trigger all components'beforeUnmountandunmountedlifecycle hooks.

4. Lifecycle Hooks

When callingapp.unmount(), Vue executes lifecycle hooks in the following order:

  1. beforeUnmount: Called before the component instance is destroyed, suitable for performing some cleanup operations.
  2. unmounted: Called after the component instance is destroyed, at this point all event listeners and child components have been removed.

Example

export default {
  beforeUnmount() {
    console.log('Component is about to be destroyed');
  },
  unmounted() {
    console.log('Component has been destroyed');
  }
}

Vue3 全局 APIVue3 Global API

Other extensions