The Application Instance
Every Vue application starts by creating a new application instance with the createApp
function:
import { createApp } from 'vue' const app = createApp({ /* root component options */ })
Mounting the Instance
Application instance must be mounted in order to render a template. This is made by calling .mount()
method, which receives as argument the container element: tag name (e.g. body
main
) or a selector (e.g. #app
.instance
).
<div id="app"></div> <script type="module"> import { createApp } from 'https://unpkg.com/vue@3/dist/vue.esm-browser.js' const app = createApp({ /* root component options */ }) app.mount('#app') </script>
Root Component
The root component can be specified using an object, or it can be imported from an SFC:
import { createApp } from 'vue' // import the root component App from a single-file component. import App from './App.vue' const app = createApp(App)
Also, we can register components globally. This way, once we register the component we can use it anywhere in the application.
app.component('MyComponent', MyComponent)
In-DOM Root Component Template
When template
option is not defined in the component, the container inner HTML is used as template. This is called «in-DOM template». It is most used on «Vue without a build step» scenarios.
<div id="app"> <button @click="count++">{{ count }}</button> </div> <script type="module"> import { createApp } from 'https://unpkg.com/vue@3/dist/vue.esm-browser.js' const app = createApp({ data() { return { count: 0 } } }) app.mount('#app') </script>
Multiple instances
We can have as many instances as we need. This is usually used in «Vue without a build step» scenarios, in order to control independently different parts of the page.
const app1 = createApp({ /* ... */ }) app1.mount('#container-1') const app2 = createApp({ /* ... */ }) app2.mount('#container-2')
Configurations
The application instance exposes a .config
object that allows us to configure a few app-level options, for example, defining an app-level error handler that captures errors from all descendant components.
app.config.errorHandler = (err) => { /* handle error */ }
Configurations must be applied befoure mounting the app. A list of possible configurations can be found here.
References