Blog>
Snippets

Understanding reactive state with ref

Demonstrate the creation and usage of a reactive state variable in a Vue 3 component using the 'ref' function.
<template>
  <div>
    <h1>{{ counter }}</h1>
    <button @click="increment">Increment</button>
  </div>
</template>
This is the HTML template of a Vue component. It displays the counter's value and a button to increment the counter. The '@click' directive adds a click event listener that calls the 'increment' method.
<script>
import { ref } from 'vue';

export default {
  setup() {
    // Creating a reactive state variable 'counter' using 'ref'
    const counter = ref(0);

    // Method to increment the counter
    function increment() {
      counter.value++;
    }

    // Expose the state and method to the template
    return { counter, increment };
  }
};
</script>
This is the Vue component's script tag using the Composition API. The 'ref' function is used to create a reactive state variable 'counter'. An 'increment' method is defined to increase the counter, and both 'counter' and 'increment' are returned from the 'setup' function to make them usable in the template.
<style scoped>
  div {
    text-align: center;
    margin-top: 20px;
  }

  h1 {
    color: #42b983;
  }

  button {
    background-color: #42b983;
    border: none;
    color: white;
    padding: 10px 20px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    font-size: 16px;
    margin: 4px 2px;
    cursor: pointer;
    border-radius: 4px;
  }
</style>
This is the scoped CSS to style the Vue component. 'scoped' ensures the styles only apply to this component. It styles the enclosing div, the h1 element for the counter value, and the increment button.