Blog>
Snippets

Ref Objects in Composition API

Implement a `ref` object from Vue's reactivity system inside the Composition API `setup` function and show how to pass its current value to the template ref.
const { ref } = Vue;

export default {
  setup() {
    // Create a 'ref' object
    const counter = ref(0);

    // Increment function to update 'counter' value
    function increment() {
      counter.value++; // Update the 'ref' object's value
    }

    // Expose the 'counter' and 'increment' to the template
    return { counter, increment };
  }
};
This code snippet demonstrates the creation of a reactive 'ref' object called 'counter' within a Vue component's 'setup' function. The 'increment' function is used to mutate the 'counter' 'ref' object's value. Both 'counter' and 'increment' are returned from the 'setup' function so they can be used inside the component's template.
<template>
  <div>
    <p>The count is: {{ counter }}</p> <!-- Display 'counter' value in the template -->
    <button @click="increment">Increment</button> <!-- Call 'increment' function on click -->
  </div>
</template>
This is the template part of the Vue component that uses the reactive 'ref' 'counter' to display its value and defines a button which, when clicked, will trigger the 'increment' function to update the 'ref' object's 'value'.