Ref vs Rreactive in Vuejs – with Examples

“ref” and “reactive” are two different ways to define reactive variables in Vue.js.

“ref” is used to define a reactive variable that refers to a single value. When the value of a “ref” variable changes, Vue.js will automatically update any parts of the user interface that depend on that variable.

Using Ref

For example, you could define a “ref” variable called “isActive” like this:

import { ref } from 'vue';

const isActive = ref(false);

// In script tag you must use the .value to access and mutate its value

isActive.value = true;

You can use it in a template like:

<template>
  <div v-if="isActive">
        // show something here
  </div>
</template>

Using Reactive

On the other hand, “reactive” is used to define a reactive object. This means that any property of the object can be tracked and updated automatically by Vue.js.
For example, you could define a “reactive” object called “user” like this:

import { reactive } from 'vue';

const user = reactive({
  first_name: 'Rizwan',
  last_name: 'Sarfraz',
  email: '[email protected]'
  age: 25,
});

Then, you can use this “user” object in your template:

<template>
  <div>
    <p>{{ user.first_name }}</p>
    <p>{{ user.last_name }}</p>
    <p>{{ user.email }}</p>
    <p>{{ user.age }}</p>
  </div>
</template>

Leave a Reply

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

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.