Intuitive Vue 3 Ref and Reactive API Examples

Last updated on by Digamber

Intuitive Vue 3 Ref and Reactive API Examples

Vue 3 is a robust framework for all your front-end development needs; it has created a special place for itself among other frontend frameworks. The flexible architecture, plugins, user-friendly APIs, and top-notch support have made it much talked about this era’s framework.

Today we will show some examples of Vue ref and reactive API; somehow, both the APIs are used to store the data and let the data be reactive profoundly.

Vue 3 Ref Example

So, we will begin this tutorial with Vue 3 ref() function. This function is known for its usefulness, and it is exorbitantly helpful in setting up a reactive variable.

Defining primitive types with Ref is effortless; here is the data types compendium that aligns with it smoothly.

  • Null
  • String
  • BigInt
  • Symbol
  • Boolean
  • Number
  • Undefined

Let’s see the Vue ref in action within the Vue component.

<template>
  <h1>{{ movieName }}</h1>
</template>

<script>
  import { ref } from "vue";

  export default {
    setup() {
      const movieName = ref("This is Vue 3!");

      setTimeout(() => {
        movieName.value = "New Movie Name";
      }, 3000);

      return { movieName };
    }
  };
</script>

The value is passed within the ref() method, and it will process the value and return back the reactive ref object.

Vue Reactive Example

So far, we have seen ref() is the suitable choice for defining reactive data on primitive values. But now we will understand the reactive() function by example; it is often used for creating a reactive object.

However, the reactive() function doesn’t work with primitive data types; instead, it returns a reactive proxy of the original by taking the object.

But you have to keep one thing in your mind that if you intend to access the reactive() function data. In that case, it will be like data.name, previously, we were directly exposing the value within the Vue template.

<template>
  <p>{{ data.name }}</p>
</template>

<script>
  import { reactive } from "vue";

  export default {
    setup() {
      const data = reactive({
        name: "This is Vue 3"
      });

      return { data };
    }
  };
</script>

Conclusion

Throughout the tutorial, we had a look at the working paradigm of Vue ref() and reactive() composition APIs. Initially, you will be confused about using these APIs, however gradually, you will recognize the power of these robust APIs and learn to play with them.