🎓 A1Learner
🔍
0 of 50 lessons completed

The ref Function

The ref function makes one value reactive in Vue. A reactive value is a value Vue tracks, so the page updates when the value changes.

Create a ref

Start with a count of zero.

import { ref } from 'vue'
const count = ref(0)

Show it in the template

The template uses the plain name.

<p>{{ count }}</p>

Change it in script

Set .value to a new number.

count.value = 5

Read it in script

Read .value to work out a new number.

const doubled = count.value * 2

Example

<script setup>
import { ref } from 'vue'
const count = ref(0)
</script>
<template>
  <div>
    <p>Count: {{ count }}</p>
  </div>
</template>

Key points

  • Call ref with a starting value, like ref(0).
  • ref wraps the value in a small holder object.
  • Read or change the value through .value in script code.
  • Write the plain name in the template, with no .value.
  • Vue updates the page when the value changes.

In this example, the script imports ref from Vue and makes a count with a starting value of 0. The template shows the count inside a paragraph. The page first shows Count: 0. If the script sets count.value to 1, the page shows Count: 1 instead.

Note

ref holds one value at a time.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does ref(0) create?