0
0
Vueframework~5 mins

Hydration behavior in Vue

Choose your learning style9 modes available
Introduction

Hydration helps Vue make a static HTML page interactive by connecting it to Vue's JavaScript code. It lets the page load fast and then become dynamic.

When you want to render your Vue app on the server for faster initial load.
When you want your app to be SEO-friendly by sending HTML to search engines.
When you want to improve user experience by showing content quickly before JavaScript runs.
When you want to keep your app interactive after server rendering without reloading the page.
Syntax
Vue
<template>
  <div>{{ message }}</div>
</template>

<script setup>
import { ref } from 'vue'
const message = ref('Hello from hydrated Vue!')
</script>
Hydration happens automatically when you use server-side rendering with Vue.
The HTML is generated on the server, then Vue attaches event listeners and reactive data on the client.
Examples
This button is server-rendered as static HTML, then Vue hydrates it so clicks update the count.
Vue
<template>
  <button @click="count++">Clicked {{ count }} times</button>
</template>

<script setup>
import { ref } from 'vue'
const count = ref(0)
</script>
The greeting text is rendered on the server and hydrated on the client for interactivity.
Vue
<template>
  <p>{{ greeting }}</p>
</template>

<script setup>
import { ref } from 'vue'
const greeting = ref('Welcome!')
</script>
Sample Program

This Vue component can be server-rendered to HTML showing the button and count. When Vue hydrates on the client, clicking the button updates the count without reloading the page.

Vue
<template>
  <button @click="increment">Clicked {{ count }} times</button>
</template>

<script setup>
import { ref } from 'vue'
const count = ref(0)
function increment() {
  count.value++
}
</script>
OutputSuccess
Important Notes

Hydration requires the server HTML and client Vue code to match exactly to avoid errors.

If the HTML differs, Vue will warn and may replace the content instead of hydrating.

Summary

Hydration connects server-rendered HTML with Vue's client code to make pages interactive.

It improves load speed and SEO by showing content before JavaScript runs.

Vue handles hydration automatically when using server-side rendering.