Vue3 app.mount() Function Detailed Explanation
In Vue3,app.mount()Its purpose is to mount the Vue application onto the DOM element.
1. Basic Structure of a Vue3 Application
In Vue3, we first need to create a Vue application instance. Usually, we can usecreateApp()function to create an application instance:
Example
import App from './App.vue';
const app = createApp(App);
In this example,createApp()The function takes a root componentAppas a parameter and returns an application instanceappNext, we need to mount this application instance onto a DOM element.
2. Purpose of the app.mount() Function
app.mount()The purpose of this function is to mount the Vue application instance onto a specified DOM element. Its syntax is as follows:
Example
Where,selectoris a string that represents the selector of the target DOM element. Vue will find the first element matching the selector and mount the application instance onto that element.
2.1 Basic Usage
Suppose our HTML file has andivelement, whoseidisapp:
Example
We can use the following code to mount the Vue application onto thisdivelement:
Example
This code will find theidisappofdivelement, and mount the Vue application instance onto that element. After mounting, Vue will start rendering the root componentAppand insert its content into thedivelement.
2.2 Notes
Selector Uniqueness:
app.mount()The function will only mount to the first element matching the selector. If there are multiple matching elements on the page, Vue will only mount to the first one.Mounting Timing:
app.mount()The function should be called after the DOM has finished loading to ensure that the target element already exists. Usually, we willwindow.onloadorDOMContentLoadedcall it in the event.app.mount()。
3. Practical Application Scenarios
3.1 Dynamic Mounting
In some cases, we may need to dynamically determine the mount point. For example, we may need to mount the application to different DOM elements on different pages or under different conditions. In this case, we can dynamically pass a selector toapp.mount():
Example
app.mount(mountElement);
3.2 Delayed Mounting
Sometimes, we may want to mount the application only at a specific point in time. For example, wait until some asynchronous operations complete before mounting the application. At this point, we can callapp.mount():
Example
app.mount('#app');
}, 3000); // Mount the application after 3 seconds
Other Extensions
Vue3 Global API