VueJS - Instances
Vue 3 - Application Instances & Root Component
Section titled “Vue 3 - Application Instances & Root Component”Every Vue application starts by creating a new application instance using the createApp function. This instance serves as the entry point for configuring and mounting your application.
Creating an Application Instance
Section titled “Creating an Application Instance”In Vue 3, you import createApp from the vue package and pass your root component’s options object to it.
// main.js (or inline script)import { createApp } from 'vue';
// Define the Root Component's optionsconst RootComponent = { // Options like data, methods, computed, setup, etc. data() { return { message: 'Hello from the Root Component!' }; }};
// Create the application instanceconst app = createApp(RootComponent);
// Mount the application instance to a DOM elementapp.mount('#app'); // Assumes <div id="app"></div> exists in your HTMLThe createApp function returns the application instance. This instance provides a context for the entire application and exposes methods for configuration (like registering components or plugins) before mounting.
The object passed to createApp defines the Root Component. This is the top-level component in your application’s component tree.
The Root Component’s Options
Section titled “The Root Component’s Options”The root component object can contain various options to define its state, behavior, and template. Here are some key options (demonstrated using both Options API and Composition API styles):
Example: Root Component Definition
Section titled “Example: Root Component Definition”<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Vue 3 App Instance</title> <script src="https://unpkg.com/vue@3"></script></head><body> <div id="vue-app"> <h1>{{ greeting }} {{ name }}!</h1> <p>Message from data: {{ message }}</p> <p>Computed reversed name: {{ reversedName }}</p> <input v-model="name" placeholder="Enter your name"> <button @click="sayHello">Say Hello (Method)</button> </div>
<script> const { createApp, ref, computed } = Vue;
const app = createApp({ // --- Composition API --- setup() { // Reactive State (like 'data' in Options API) const name = ref('Vue User'); const message = ref('This is a reactive message.'); const greeting = 'Welcome'; // Non-reactive variable
// Computed Properties const reversedName = computed(() => { return name.value.split('').reverse().join(''); });
// Methods function sayHello() { alert(`Hello, ${name.value}!`); }
// Expose to template return { name, message, greeting, reversedName, sayHello }; },
// --- Options API (Still valid in Vue 3) --- /* data() { return { name: 'Vue User', message: 'This is a reactive message.', greeting: 'Welcome' }; }, computed: { reversedName() { return this.name.split('').reverse().join(''); } }, methods: { sayHello() { alert(`Hello, ${this.name}!`); } }, */ // Lifecycle hooks, components, directives etc. can also be defined here mounted() { console.log('App mounted!'); // Access Composition API state via 'this' if setup returns object console.log('Initial name:', this.name); } });
app.mount('#vue-app');
// Accessing instance data (less common now, mainly for debugging) // const vm = app.mount('#vue-app'); // console.log(vm.name); // Access Composition API refs // console.log(vm.$data.message); // If using Options API data
</script></body></html>Key Options Explained
Section titled “Key Options Explained”setup()(Composition API): The entry point for Composition API. Define reactive state (ref,reactive), computed properties (computed), methods (plain functions), and lifecycle hooks here. Return an object to expose values and functions to the template.data()(Options API): A function that returns an object containing the component’s reactive state. Properties are accessible viathisin other options and are automatically available in the template.methods(Options API): An object where keys are method names and values are functions. Methods have access to the component instance viathis.computed(Options API): An object for defining computed properties. These are cached based on their reactive dependencies. Accessed like data properties viathis.props: An array or object defining properties the component can receive from a parent. (More relevant for child components, but can technically be used on root).- Lifecycle Hooks: Functions like
mounted,created,updated,unmountedthat allow you to execute code at specific stages of the component’s lifecycle. (Available in both APIs). components: An object for registering child components locally within this component.directives: An object for registering custom directives locally.
Template (template option or In-DOM)
Section titled “Template (template option or In-DOM)”The component’s template can be defined in several ways:
- In-DOM Template (used in examples): If the element targeted by
app.mount()(e.g.,<div id="vue-app">) contains HTML content, Vue uses that as the template. templateString Option: Add atemplate: '...'property to the component options object containing the HTML string.- Single File Components (.vue files): The standard approach in build setups, where the template, script, and styles are colocated in a
.vuefile. This is highly recommended for maintainability.
Multiple Application Instances
Section titled “Multiple Application Instances”You can create multiple independent Vue application instances on the same page, each controlling a different part of the DOM. This is less common for SPAs but can be useful for integrating Vue into server-rendered pages.
// App 1createApp({ ... }).mount('#app1');
// App 2 (independent)createApp({ ... }).mount('#app2');Application Configuration (app.component, app.directive, app.use)
Section titled “Application Configuration (app.component, app.directive, app.use)”The application instance (app) provides methods to configure your application globally before mounting:
app.component('component-name', ComponentDefinition): Register a global component.app.directive('directive-name', DirectiveDefinition): Register a global custom directive.app.use(Plugin, options?): Install a Vue plugin (like Vue Router or Pinia).
Understanding the application instance and the root component is the first step in building any Vue application.