Blog>
Snippets

Using Vue 3's Reactive Composition API for State Management

Showcase how to manage and track state within Vue 3's composition API using reactive references.
import { reactive, toRefs } from 'vue';

export function useCounter() {
  // Reactive state object
  const state = reactive({
    count: 0
  });

  // Increment function to mutate state
  function increment() {
    state.count++;
  }

  // Expose state and functions
  return { ...toRefs(state), increment };
}
Define a reusable composition function (useCounter) that encapsulates the state and functionalities. 'reactive' is used to create a reactive state object, and 'toRefs' is used to convert each property on the reactive object to a ref, which maintains reactivity when destructured. The increment function mutates the count property.
<script setup>
import { useCounter } from './useCounter';

// Using the composition function in a component
const { count, increment } = useCounter();
</script>

<template>
  <button @click="increment">Count is: {{ count }}</button>
</template>
This is how the composition function 'useCounter' can be incorporated in a component. The script uses the 'setup' attribute to indicate it's leveraging Vue 3's composition API. It imports the composition function and destructures the returned reactive references and functions to use in the template.