Vue Declarative Rendering
The core of Vue is its declarative rendering system. Unlike imperative programming (manipulating DOM directly, like using jQuery $('#id').text('new text')), declarative rendering allows you to only care about the relationship between State and View, leaving the tedious DOM operations to the framework.
What is Declarative Rendering?
Simply put, you only need to declaratively describe: "When my data is like this, my page should be like this."
When the data changes, Vue will automatically and efficiently update the view to keep it in sync with the new data state. This process is reactive.
Let's understand this through an example.
Core: State and Template
In Vue, we mainly deal with two parts:
- JavaScript State: Your application's data.
- HTML Template: Your view structure.
Vue connects them together.
App.vue
<script setup>
// 1. Import ref to create reactive state
import { ref } from 'vue'
// 2. Define a reactive variable (state)
const counter = ref(0)
// 3. Define a method to change this state
function increment() {
counter.value++
}
</script>
<template>
<!-- 4. Render state into the view -->
<h1>Count is: {{ counter }}</h1>
<!-- 5. Bind an event to call a method, thus changing state -->
<button @click="increment">Increment</button>
</template>Let's break down this process:
State (
counter): We usedref(0)to create a reactive variablecounter.refis part of Vue 3's Composition API. It accepts an internal value and returns a reactive, mutable ref object. This object has a.valueproperty that points to the internal value.View (
<template>): In the template, we useto display the value ofcounter. Vue knows that the content of<h1>depends oncounter.Action (
incrementmethod): We defined anincrementfunction that modifies the value ofcounter(counter.value++). We bind this function to the button's click event using@click(shorthand forv-on:click).
How Does It Work?
Initial Render: When the component first loads, Vue renders the template. It sees
, reads the value ofcounter.value(which is 0), and renders it into<h1>. While readingcounter, Vue records this dependency: the content of<h1>depends oncounter.State Change: When you click the button, the
incrementfunction is called, andcounter.valuebecomes 1.Auto Update: Because
counteris a reactive reference, when its value is modified, Vue's reactivity system is notified. The system checks all places that depend oncounterand notifies them to update.Efficient DOM Update: Vue discovers that the content of
<h1>needs to be updated, so it efficiently operates on the DOM, updating the text content of<h1>from "Count is: 0" to "Count is: 1".
This is the magic of declarative rendering. You no longer need to manually write code like document.getElementById(...).textContent = .... You just need to manage your state well, and Vue will ensure your view always stays in sync with your state, making your code more concise, easier to understand, and maintain.