Intuitive Vue 2 Ref And Reactive API Examples

Vue Js Ref And Reactive API Examples; Vue is a robust framework for all our front-end development needs.

Some features that make Vue Js unique are its flexible architecture, plugins, user-friendly APIs and many more.

Today, in this tutorial, we will see some examples of Vue ref and reactive API. Both the APIs are used to store the data and let the data be reactive profoundly.

 

Vue Ref Example

The beginning of this Vue js tutorial has to be started with the Vue ref() function. This function is known for its usefulness and it is very helpful in setting up a reactive variable.

Defining primitive types with Ref is effortless. Below is the data types compendium that aligns with it smoothly:

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

 

Below given is 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!");
      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

Till now, we have seen ref() as the suitable choice for defining receive data on primitive values. Thereafter, 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 do remember that if we intend to access the reactive() function data, then 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"
      });
      return { data };
    }
  };
</script>

 

Conclusion

Throughout this Vue js guide, we have seen the working paradigm of Vue ref() and reactive() composition APIs.

 

Thanks

Leave a Reply

Your email address will not be published. Required fields are marked *