Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Vue 3 app.mount() Function

Vue 3 app.mount() Function Explained


Vue3 Global API Vue 3 Global API

In Vue 3,app.mount() 's role is to mount the Vue application onto a DOM element.


1. Basic Structure of a Vue 3 Application

In Vue 3, we first need to create a Vue application instance. Typically, we use createApp() function to create an application instance:

Example

import

{

createApp

}

from

'vue'

;

import

App from

'./App.vue'

;

const

app

=

createApp

(

App

)

;

In this example,createApp() The function receives a root component App as a parameter and returns an application instance app. Next, we need to mount this application instance onto a DOM element.


2. The Role of the app.mount() Function

app.mount() The function's role is to mount the Vue application instance onto a specified DOM element. Its syntax is as follows:

Example

app.

mount

(

selector

)

;

Whereselector is a string representing the selector of the target DOM element. Vue finds the first element matching the selector and mounts the application instance onto it.

2.1 Basic Usage

Suppose our HTML file has a div element with its id is app:

Example

We can mount the Vue application onto this div element with the following code:

Example

app.

mount

(

'#app'

)

;

This code finds the id is app 's div element and mounts the Vue application instance onto it. After mounting, Vue starts rendering the root component Appand inserts its content into the div element.

2.2 Notes


3. Practical Application Scenarios

3.1 Dynamic Mounting

In some cases, we may need to dynamically decide the mount point. For example, we may need to mount the application to different DOM elements under different pages or conditions. In that case, we can dynamically pass the selector to app.mount():

Example

const

mountElement

=

condition

?

'#app1'

:

'#app2'

;

app.

mount

(

mountElement

)

;

3.2 Delayed Mounting

Sometimes, we may want to mount the application at a specific point in time—for example, after waiting for some asynchronous operations to complete. In that case, we can call app.mount():

Example

setTimeout

(

(

)

=>

{

  app.

mount

(

'#app'

)

;

}

,

3000

)

;

// mount the application after 3 seconds


Vue3 Global API Vue 3 Global API