0
0
Vueframework~5 mins

Reactive data with ref in Vue

Choose your learning style9 modes available
Introduction

We use ref to create reactive data that Vue can track and update the UI automatically when it changes.

When you want to store a simple reactive value like a number or string.
When you need to update the UI automatically after changing a variable.
When you want to keep track of a value that changes over time, like a counter.
When you want to share reactive data inside a component using the Composition API.
When you want to create reactive references to DOM elements.
Syntax
Vue
import { ref } from 'vue';

const variable = ref(initialValue);

ref wraps a value and returns a reactive object with a .value property.

You read and write the actual value using .value.

Examples
Create a reactive number and update it.
Vue
import { ref } from 'vue';

const count = ref(0);

count.value = 5; // update the value
Create a reactive string and read its value.
Vue
import { ref } from 'vue';

const message = ref('Hello');

console.log(message.value); // prints 'Hello'
Use a reactive boolean to control UI visibility.
Vue
import { ref } from 'vue';

const isVisible = ref(true);

isVisible.value = false;
Sample Program

This Vue component shows a number and a button. When you click the button, the number increases by 1 automatically because count is reactive using ref.

Vue
<template>
  <div>
    <p>Count: {{ count }}</p>
    <button @click="increment">Add 1</button>
  </div>
</template>

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

const count = ref(0);

function increment() {
  count.value++;
}
</script>
OutputSuccess
Important Notes

Always use .value to access or change the value inside a ref.

Vue tracks changes to ref values and updates the UI automatically.

Use ref for simple values; use reactive for objects or arrays.

Summary

ref creates reactive data Vue can track.

Access and update the value with .value.

Use it to make UI update automatically when data changes.