JAVASCRIPT
Synchronizing Document Title Reactively with Vue 3 `watchEffect`
Learn to use Vue 3's `watchEffect` to automatically update the browser's document title based on reactive state, ensuring your page titles are always in sync.
// MyComponent.vue
<template>
<div>
<h1>Page Title Synchronizer</h1>
<label for="page-title-input">Enter New Page Title:</label>
<input type="text" id="page-title-input" v-model="pageTitle" />
<p>Current Reactive Title: <strong>{{ pageTitle }}</strong></p>
<p>Check your browser tab to see the updated document title!</p>
</div>
</template>
<script setup>
import { ref, watchEffect } from 'vue';
const pageTitle = ref('Home Page');
// watchEffect automatically tracks pageTitle and re-runs when it changes
watchEffect(() => {
document.title = `My App | ${pageTitle.value}`;
});
</script>
<style scoped>
input {
padding: 8px;
margin: 10px 0;
border: 1px solid #ddd;
border-radius: 4px;
width: 300px;
display: block;
}
h1 {
color: #333;
}
p {
color: #555;
}
</style>
How it works: This snippet showcases `watchEffect`, a powerful Vue 3 Composition API function for automatically re-running side effects based on reactive state changes. Here, `watchEffect` is used to synchronize the browser's `document.title` with the reactive `pageTitle` ref. Unlike `watch`, `watchEffect` doesn't require explicitly specifying dependencies; it automatically tracks any reactive properties accessed within its callback and re-executes whenever those properties change. This ensures the document title is always up-to-date with the component's state without manual dependency management.