Vue.js Core Archi: Virtual DOM & Reactivity

πŸ’‘ Vue.js Core Archi: Virtual DOM & Reactivity β€” Executive Summary

Technical architectural analysis, practical configuration manifests, and deployment instructions for Vue.js Core Archi: Virtual DOM & Reactivity.

Related pages
Implements
Using

Operation sequence

References and Guidelines (NOTE)

Run on the client (browser)

  1. Create a Vue instance: Create a Vue instance with new Vue() in main.js and mount it on the DOM.
javascript
import Vue from 'vue';
   import App from './App.vue';

   new Vue({
     render: h => h(App),  // App.vue νŒŒμΌμ„ λ Œλ”λ§
   }).$mount('#app');      // μ• ν”Œλ¦¬μΌ€μ΄μ…˜μ„ #app μš”μ†Œμ— 마운트
  1. Root component loading: The root component is loaded and rendered.
javascript
new Vue({
     render: h => h(App),  // 루트 μ»΄ν¬λ„ŒνŠΈλ₯Ό λ Œλ”λ§
   }).$mount('#app');
  1. Compile template and create virtual DOM: Template is converted to virtual DOM, and Vue sets up data binding.
javascript
<template>
     <div>
       <h1>{{ message }}</h1>
     </div>
   </template>
  1. Execute lifecycle hook: The component’s lifecycle hook is executed, data is set and mounted in the DOM.
  2. beforeCreate(): Called before the Vue instance is initialized. No data or events have been set yet.
  3. created(): Called after the instance is created, data is set and the reactive system starts working.
  4. beforeMount(): Called just before the virtual DOM is mounted on the real DOM.
  5. mounted(): Called after the virtual DOM is mounted on the real DOM. At this stage, the component is fully rendered and displayed on the screen.
  6. Directive binding and two-way data binding: Directives (v-model, v-bind, etc.) are bound to components.
  7. v-model: Synchronizes user input with data from the Vue instance.
  8. v-bind: Binds data attributes to attributes of HTML elements.
  9. v-if, v-for: Provides conditional rendering and iterative rendering.
javascript
<template>
     <div>
       <input v-model="message" />
       <p>{{ message }}</p>
     </div>
   </template>

   <script>
   export default {
     data() {
       return {
         message: 'Hello Vue!'
       };
     }
   };
   </script>
  1. Synchronization of virtual DOM and real DOM: When data changes, changes are made to real DOM through virtual DOM
References and Guidelines (NOTE)

Whenever data changes, Vue first updates the virtual DOM, compares the virtual DOM and the real DOM, and reflects only the changed parts in the real DOM. This process is called DOM Diffing.

  • When data changes, Vue updates the virtual DOM and **patches** the changed parts to reflect them in the real DOM. This approach efficiently only applies changes without re-rendering the entire DOM.
  1. Vue Router and Vuex (optional)
  2. Vue Router:
    • Vue Router is responsible for managing routing in SPA (Single Page Application).
    • When the application loads, the router-view component renders the components appropriate for the current route.
javascript
const router = new VueRouter({
        routes: [
          { path: '/home', component: HomeComponent },
          { path: '/about', component: AboutComponent }
        ]
      });

      new Vue({
        router,
        render: h => h(App)
      }).$mount('#app');
  1. Vuex:

    – Vuex is responsible for state management of the application and manages data with a centralized state store.
    – Vuex sets the state during the initialization process and binds the state so that the component can use it.

    javascript
    const store = new Vuex.Store({
         state: {
           count: 0
         },
         mutations: {
           increment(state) {
             state.count++;
           }
         }
       });
    
       new Vue({
         store,
         render: h => h(App)
       }).$mount('#app');
  1. Re-rendering when data changes

    Vue operates based on a reactive system, so the component is re-rendered whenever the data changes. Vue compares the virtual DOM and the real DOM and applies only the changed parts to the DOM, minimizing performance degradation.

  2. When the component is destroyed (release phase)

    Vue’s release phase runs when a component is no longer needed or is moved to a different route.

  • beforeDestroy(): Called before the component is destroyed.
  • destroyed(): Called after the component is destroyed, and any event listeners or data bindings are released.

Option Properties

  • Example:
  • Data Options:

    – data
    – props
    – computed
    – methods

  • State Management:

    – setup
    – provide
    – inject

  • Lifecycle Hooks:

    – beforeCreate
    – created
    – beforeMount
    – mounted
    – beforeUpdate
    – updated
    – beforeUnmount (Vue 3)
    – unmounted (Vue 3)
    – activated
    – deactivated
    – errorCaptured

  • Rendering Options:

    – render
    – renderTracked
    – renderTriggered

  • Watchers:

    – watch

  • Directives and Components:

    – directives
    – components
    – mixins
    – extends

  • Template-related Options:

    – template
    – delimiters

  • Other Options:

    – name
    – inheritAttrs
    – emits
    – model
    – filters (deprecated in Vue 3)

Lifecycle hook
created() VS mounted()
References and Guidelines (NOTE)

1. The API call from created() starts fetching data before the DOM is rendered, allowing the data to be ready when the DOM is mounted. This improves the user experience and makes pages feel faster to load.
2. A clearer and more structured design where created() initializes data, and mounted() handles only DOM-related operations.
3. Separation of responsibilities

Features created() mounted()
Point of view Immediately after the component is created, before it is mounted in the DOM After the component is fully mounted in the DOM
DOM accessible impossible possible
Mainly used Data initialization, API call DOM manipulation, animation, external library initialization
Practical usage example Setting status or data Access the DOM through this.$refs, etc.
Other options
computed vs watch
characteristics computed watch
Basic Purpose Returns the calculated value of responsive data Perform secondary actions when data changes
Main Features Caching: Returns cached value if value does not change Actions that react directly to data changes (asynchronous operations, etc.)
Caching O (recalculate only when dependent data changes) X (executes immediately whenever data changes)
When to use When operation between data is required When data changes When performing a specific action
Asynchronous operations X O (API calls, timer settings, etc.)
Return value O X (only performs minor tasks)
Setter support O (can be set if desired) X
References and Guidelines (NOTE)

When to use computed and when to use watch?

  • If you usecomputed:
  • When you need complex calculated values and want those values to be cached.
  • For example, when operations between multiple data are required, but there is no need to recalculate them each time and updates are needed only when the data changes.
  • If you use watch:
  • When there is a side task that needs to be executed when certain data changes.
  • When you need to execute operations such as asynchronous operations or API calls according to data changes.
  • When you need to track changes in data in real time and respond immediately.
References and Guidelines (NOTE)

Execution order when identical values are defined

  • computedruns first
  • computed properties are recomputed immediately when the data they depend on changes, and Vue’s reactive system keeps track of the data during this process. If the cached computed value is no longer valid, this value is first recomputed.
  • watch runsafter computed.
  • A watch is a hook that executes secondary tasks after data has changed. Vue detects data changes and then runs a watch when the change is complete to perform any necessary side work.

Instance Properties

  • Example:
  • $data: Access the responsive data object of the component.
  • $props: Access \*\*props\*\* passed from the parent component.
  • $el: Access the DOM element where the component is mounted.
  • $refs: Access to specific DOM elements or child components within a component.
  • $emit: Emits an event in a child component.
  • $nextTick: Executes callback in next rendering cycle after DOM update.
  • $watch: Detects changes in specific data properties and executes callbacks.
  • $on, $off, $once: Registering and deregistering event handlers.
  • $parent: Access the parent component.
  • $children: Access child components.
  • $slots: Access slot content.
  • $store: Access the Vuex store (when using Vuex).
  • $router: Access to Vue Router (when using Vue Router).
  • $route: Access current route information (when using Vue Router).

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *