Blog>
Snippets

Using the Reactive Function

Explain how to use the reactive function to create a reactive state object in Vue.js 3 Composition API.
<template>
  <div>
    <h1>{{ state.count }}</h1>
    <button @click="increment">Increment</button>
  </div>
</template>

<script>
import { reactive, toRefs } from 'vue';

export default {
  setup() {
    // Create a reactive state object
    const state = reactive({
      count: 0
    });

    // Increment function modifies the state
    function increment() {
      state.count++;
    }

    // Expose state to the template
    // Using toRefs to ensure reactivity is preserved
    return { ...toRefs(state), increment };
  }
};
</script>
The code defines a Vue component with a reactive state object that contains a property 'count'. It uses Vue's Composition API including the 'reactive' and 'toRefs' functions. 'reactive' is used to make the state object reactive, and 'toRefs' is used to maintain reactivity when properties are de-structured and returned from the 'setup' function. The component has a template that displays the 'count' and a button that when clicked, will increment the count.
<style>
div {
  text-align: center;
  margin-top: 50px;
}

button {
  font-size: 20px;
  padding: 10px 20px;
}
</style>
The accompanying CSS styles center the text and button within the div and adds styling to the button to improve its appearance.