Blog>
Snippets

State Management with Vue 3 Composition API - Refs

Explain how to manage state using refs in the Vue 3 Composition API and how it differs from reactive state.
import { ref } from 'vue';

export default {
  setup() {
    // Declare a ref state called counter with an initial value of 0
    const counter = ref(0); 
 
    // Define a method to increment the counter
    function increment() {
      counter.value++; // Note the use of .value to access the reactive value
    }

    // Return the state and the method to the context where this composition function is used
    return { counter, increment };
  },
};
This code snippet demonstrates how to use the `ref` function from Vue 3's Composition API to create a reactive state variable. The variable `counter` is declared as a reactive reference to an integer. The `.value` property is used to read and update its underlying value. The `increment` function when called will mutate the state of `counter` by increasing its value by one. Both `counter` and `increment` are exposed to the component's template, where `counter` can drive dynamic content and `increment` can be used as an event handler.
<template>
  <button @click="increment">Increment</button>
  <p>Counter: {{ counter }}</p>
</template>

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

const counter = ref(0);

function increment() {
  counter.value++;
}
</script>
In this Vue component template, we have a button that, when clicked, will call the `increment` method. Additionally, the value of `counter` is displayed in a paragraph element. In the accompanying script setup block, the `ref` function is imported from Vue, which is used to create a reactive state variable called `counter`. The `increment` method updates the value of `counter` by accessing and modifying `counter.value`. This updated value will automatically be reflected in the displayed paragraph due to Vue's reactivity system.