Vue3 Fundamentals · Reactivity

Hold a value with ref

ref

Hold a value with ref

You change a value in your component and the page keeps showing the old one. A plain variable cannot fix that: Vue only re-renders when it knows a value it rendered has changed, and a plain variable tells it nothing.

Wrap the value in ref to make it reactive. Vue then tracks every place the value is read and re-renders when it changes:

<script setup>
import { ref } from 'vue';

const count = ref(0);
</script>

<template>
  <button @click="count++">Count: {{ count }}</button>
</template>

ref returns an object with one property, .value, that holds the value. In JavaScript you read and write it through .value:

count.value += 1;

In the template you drop .value — Vue unwraps it for you, so {{ count }} shows the number and count++ updates it. That is why the button's label follows every click.

The Test for this Lesson mounts your component, clicks the button once, and checks the label. Your component is exported from App.vue.

Challenge

The button shows Count: 0 and never moves. Store the count in a ref so Vue re-renders when it changes: export an App component from App.vue that renders a button labelled Count: 0 and adds one to the count on each click.

The Test mounts your component, clicks the button once, and expects the label to read Count: 1. The starter keeps the count in a plain variable, so the label never updates and the Test fails.

App.vue
<script setup>
let count = 0;
</script>

<template>
  <button @click="count++">Count: {{ count }}</button>
</template>

No test run yet

The Test is hidden. Run it to check the Challenge — you only see the result, never the test source.