Search⌘ K

Dealing with Data: ref() and reactive()

Explore how to manage component state in Vue 3 using ref() for primitive values and reactive() for objects. Learn how their reactivity works within the setup() method and how changes automatically update the template and component state.

Overview

What about working with the component state if there’s no access to the instance? Vue 3 provides tools for creating reactive data within the setup() method.

The ref() function

The ref() function is used to create reactive primitive values (such as strings, numbers, booleans, and so on). It creates a wrapper around the value, allowing it to be passed by reference:

Javascript (babel-node)
import { ref } from 'vue';
export default {
setup() {
const isLoggedIn = ref(false);
console.log(isLoggedIn.value); // output: false
}
}

As we can see in the example above, in order to access (or update) the value of a ref, we have to use the .value property. This is only necessary from within our JavaScript code; within the template, the value is automatically handled.

Code example

...