Vue 3.0 ref differs from reactive

the use of ref

ref the role is to convert a primitive data type into a data type with a reactive attribute (reactivity), there are 7 primitive data types, which are:

  • String
  • Number
  • Boolean
  • Null
  • Undefined
  • Symbol : It is used to generate a unique value, it is often used in Symbol data to assign values to object properties, so that object properties are unique and not easily overwritten.
  • BigInt : Solves the problem of missing precision by providing a way to represent integers greater than 2^53-1. BigInt can represent an integer of any size

Compared with Vue2, the advantage of using ref is that you can no longer write this when passing values

<template>
  <img alt="Vue logo" src="./assets/logo.png" />
  <h1>{{ title }}</h1>
  <button @click="handleClick">Click</button>
</template>

<script lang="ts">
import { defineComponent, ref } from "vue";

export default defineComponent({
  name: "App",
  setup() {
    const title = ref("Hello, Vue3!");
    const handleClick = () => {
      title.value = "JavaScript";
    };
    return { title, handleClick };
  },
});
</script>

the use of reactive

Vue3 provides a method: (equivalent to Vue.observable() in Vue2 ) to give objects a reactive property, then we can rewrite the above code in the form of an object as:reactive

<template>
  <img alt="Vue logo" src="./assets/logo.png" />
  <h1>{{ data.title }}</h1>
  <button @click="data.handleClick">Click</button>
</template>

<script lang="ts">
import { defineComponent, reactive } from "vue";

export default defineComponent({
  name: "App",
  setup() {
    const data = reactive({
      title: "Hello, Vue3",
      handleClick: () => {
        data.title = "JavaScript";
      },
    });
    return { data };
  },
});
</script>

The role of toRefs is to omit data

<template>
  <img alt="Vue logo" src="./assets/logo.png" />
  <h1>{{ title }}</h1>
  <button @click="handleClick">Click</button>
</template>

<script lang="ts">
import { defineComponent, reactive, toRefs } from "vue";

export default defineComponent({
  name: "App",
  setup() {
    const data = reactive({
      title: "Hello, Vue3",
      handleClick: () => {
        data.title = "JavaScript";
      },
    });
    const dataAsRefs = toRefs(data);
    /*
    Type of dataAsRefs:
    {
        title: Ref<string>,
        handleClick: Ref<() => void>
    }
    */
    return { ...dataAsRefs };
  },
});
</script>   

summary

ref and one for raw data types and the other for objects, both APIs are designed to give responsive features to JavaScript’s normal data types (reactivity)

whether to use ref or reactive can choose such a guideline

  1. Just as with the native javascript code, choose whether to use ref or reactive, just as you would if you were writing normal js code to choose between primitive types and object types.
  2. Use in all scenarios, but remember to use to ensure that object properties remain responsive.

Leave a Reply