Reactivity Part 1
Vue provides a great reactivity system that tracks changes to the data and triggers updates automatically, allowing you to have your UI always up-to-date with the data. Vue's reactivity comes with a few primitives: ref
, reactive
, computed
and watch
.
ref()
creates a container to hold a single value, that can be tracked automatically when the value changes. The value can be accessed or updated via.value
property.computed()
takes a getter function and returns aref
object, that reflects the return value of the getter function.
Here in the playground, we've created a ref object named count
to hold a number, and a computed object named double
that calculates the double of count
. Vue will smartly know that double
depends on count
, so whenever count
changes, double
will re-calculate automatically.
Try clicking the button to increase the count
value - you will see that the value of double
also reflects the change.
Note: Refs will be auto unwrapped by Vue when referenced in the <template>
, The .value
is only needed when accessing the ref in <script>
or JavaScript outside of Vue components.
Challenge
Now let's get our hands on it! Try modifying the code to make the multiplier also reactively updatable (current hard-coded as 2
).
To do that, you can:
- Create a variable named
multiplier
withref()
and set it to2
- Rename
double
toresult
in both the<script>
and<template>
- Update the implementation of
result
to returncount.value * multiplier.value
- Add another button to increase the
multiplier
value
That's it! Now when you click the multiplier button, you will see the result get changed with the new multiplier.
If you get stuck, you can check the solution by clicking the button below, or on the top-right corner of the editor.
Feel free to play more to explore your ideas! Once you're are done, let's move on to the next section to learn a bit more about the reactivity system.