0
0
Vueframework~30 mins

Watch and watchEffect in Vue - Mini Project: Build & Apply

Choose your learning style9 modes available
Reactive Counter with watch and watchEffect in Vue
📖 Scenario: You are building a simple counter app using Vue 3. You want to learn how to react to changes in your data using watch and watchEffect.This will help you update other values or run side effects automatically when your counter changes.
🎯 Goal: Create a Vue component that has a reactive count variable. Use watch to log a message when count changes. Use watchEffect to update a doubleCount variable automatically when count changes.
📋 What You'll Learn
Use Vue 3 Composition API with <script setup>
Create a reactive variable count initialized to 0
Create a reactive variable doubleCount initialized to 0
Use watch to log the new count value whenever it changes
Use watchEffect to update doubleCount to be twice the count
Render buttons to increment and decrement count
Display count and doubleCount in the template
💡 Why This Matters
🌍 Real World
Watching reactive data is common in Vue apps to run side effects like API calls, logging, or updating other data automatically.
💼 Career
Understanding watch and watchEffect is essential for Vue developers to build responsive and efficient user interfaces.
Progress0 / 4 steps
1
Setup reactive count and doubleCount
Create a Vue component with <script setup>. Inside it, import ref from 'vue'. Then create a reactive variable called count initialized to 0 and another reactive variable called doubleCount initialized to 0.
Vue
Need a hint?

Use ref(0) to create reactive variables for count and doubleCount.

2
Add buttons to change count
In the <template>, add two buttons: one with a click event that increments count by 1, and another with a click event that decrements count by 1.
Vue
Need a hint?

Use @click="count++" and @click="count--" on the buttons to change count.

3
Use watch to log changes to count
Import watch from 'vue'. Use watch to watch the count variable. Inside the watcher function, log the new value of count to the console with the message: `Count changed to: ${newValue}`.
Vue
Need a hint?

Use watch(count, (newValue) => { ... }) to react to changes in count.

4
Use watchEffect to update doubleCount
Import watchEffect from 'vue'. Use watchEffect to automatically update doubleCount.value to be count.value * 2 whenever count changes.
Vue
Need a hint?

Use watchEffect(() => { doubleCount.value = count.value * 2 }) to keep doubleCount updated.