Reactivity Part 2
In the previous section, we learned about ref and computed. In this section, we will learn about reactive and watch that fulfill our basic needs for reactivity.
reactive()
While ref() wraps a single value, reactive() makes an entire object reactive. This is useful when you have multiple related values to track together.
<script setup>
const user = reactive({
name: 'John',
age: 30,
city: 'Paris'
})
// You can access properties directly without .value
function updateAge() {
user.age++
}
</script>
Note: Unlike ref, you don't need .value to access or modify properties of reactive objects. However, reactive only works with objects (including arrays), not primitive values like numbers or strings.
watch()
The watch() function allows you to perform side effects in response to reactive state changes. It's perfect for tasks like:
- Fetching data when a value changes
- Saving to localStorage
- Logging or debugging
- Triggering animations
<script setup>
const count = ref(0)
watch(count, (newValue, oldValue) => {
console.log(`Count changed from ${oldValue} to ${newValue}`)
})
</script>
You can also watch multiple sources:
watch([count, multiplier], ([newCount, newMultiplier]) => {
console.log(`Count: ${newCount}, Multiplier: ${newMultiplier}`)
})
watchEffect()
watchEffect() is similar to watch, but automatically tracks all reactive dependencies used inside the callback:
<script setup>
const count = ref(0)
const multiplier = ref(2)
watchEffect(() => {
console.log(`Result: ${count.value * multiplier.value}`)
})
</script>
Challenge
In the playground, we have a counter with a multiplier and a computed result. Your task is to add a watcher that logs a message to the console whenever the result changes.
To complete the challenge:
- Add a
watch()that monitors theresultcomputed property - In the watch callback, log a message like:
"The result is now: X"where X is the new value - Click the buttons and open the browser console to see your logs
Tip: Remember that computed values can be watched just like ref values!
If you get stuck, you can check the solution by clicking the button below.
Great work! You now understand the core reactivity primitives in Vue. Next, we'll explore the component lifecycle.