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 a ref 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:

  1. Create a variable named multiplier with ref() and set it to 2
  2. Rename double to result in both the <script> and <template>
  3. Update the implementation of result to return count.value * multiplier.value
  4. 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.

Vue Basics
Nuxt integrates Vue 3, a progressive framework for building user interfaces. In this section, we will cover the basics of Vue.
Reactivity Part 2
In the previous section, we learned about ref and computed. In this section, we will learn about reactive and watch that fullfills our basic needs for reactivity.
Files
Editor
Initializing WebContainer
Mounting files
Installing dependencies
Starting Nuxt server
Waiting for Nuxt to ready
Terminal