Vue 3 app.unmount() Function
In Vue 3,app.unmount() is used to unmount (i.e., destroy) an already-mounted Vue application instance.
app.unmount() is a very useful function in Vue 3 that allows you to safely destroy a Vue application instance and release related resources.
1. What is the app.unmount()?
app.unmount() is a global API provided by Vue 3 for unmounting an already-mounted Vue application instance. When you call this function, Vue performs the following operations:
- Destroy all component instances.
- Remove all event listeners.
- Clear all DOM elements related to the application.
Simply put,app.unmount() removes the entire Vue application from the page and releases all related resources.
2. Why Do We Need app.unmount()?
In certain 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 current page's Vue application instance to avoid memory leaks.
- Dynamically loaded components: In scenarios involving dynamic loading and unloading of components,
app.unmount()can help you safely destroy component instances that are no longer needed. - Test environment: In unit or integration tests, you may need to destroy the Vue application instance after each test to ensure test independence and accuracy.
3. How to Use app.unmount()?
Use app.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 the Vue application
app.
mount
(
'#app'
)
;
// unmount the Vue application
app.
unmount
(
)
;
Code analysis:
- Create application instance: First, we used
createApp()function to create a Vue application instance and passed in the root componentApp. - Mount application: Then, we called
app.mount('#app')to mount the application onto the page's#appelement. - Unmount the application: Finally, we called
app.unmount()to unmount the application from the page.
Notes:
- Mount point: When calling
app.mount(), the specified mount point (e.g.,#app), after callingapp.unmount(), Vue will clear it. - Component lifecycle: Calling
app.unmount()triggers all components'beforeUnmountandunmountedlifecycle hooks.
4. Lifecycle Hooks
When calling app.unmount() , Vue executes the lifecycle hooks in the following order:
- beforeUnmount: Called before the component instance is destroyed; suitable for performing cleanup operations.
- unmounted: Called after the component instance is destroyed, when all event listeners and child components have already been removed.
Example
export
default
{
beforeUnmount
(
)
{
console.
log
(
'Component is about to be destroyed'
)
;
}
,
unmounted
(
)
{
console.
log
(
'The component has been destroyed'
)
;
}
}
Vue 3 Global API