This is the sixth day of my participation in the First Challenge 2022. For details: First Challenge 2022.

Vue3 slowly learn series! 🙉

preface

In Vue2. X, data is defined in data, but in Vue3, we can define it directly in setup. Such as:

<template>
  <div>{{num}}</div>
</template>

<script setup>
  let num = 0;
</script>
Copy the code

There is a problem, however, with num being nonreactive. That is, after num is dynamically changed, the initial value 0 is always displayed on the interface. You can do a simple test

🎨 effect:

As you can see, when the num value changes, the view does not update.

ref

In Vue 3.0, we can solve this problem by using the ref function.

<template> <button @click="count"> </button> <div> {{num}}</div> </template> <script setup> import { ref } from 'vue' let num = ref(0) function count() { num.value++ Console. log(' current result ',num.value)} </scriptCopy the code

Effect after use:

💥 note:

We can see this in the example above

  • After the value is wrapped by ref, we change num to usenum.value.

This is because ref takes the parameter and returns it wrapped in an object with a value property, which is then used to access or change the value of the reactive variable.

💡 extension:

We created the response above for data of the base type ref, but what about an object or array? Ref also applies, and you can look at this with an example

🎨 Results show:

(Wait a few seconds)

Comparison of results:

reactive

Although ref can be used to define both the base string and number types and the complex reference array and object types, reactive is often used to define objects.

The difference and relation between REF and Reactive

  • In general, ref is used to define simple strings or values, and Reactive is used to define arrays of objects, etc.

  • When ref defines data, it makes a layer of judgment about the data types inside it, and reactive is used to handle complex reference types.

  • You can use refs to define object arrays and so on, but you are warned if you use Reactive to define basic types.

References:

Vue ref

Vue reactive


🎨 [thumbs up] [concerns] don’t get lost, more front-end dry goods waiting for you to unlock

Phase to recommend

👉 JavaScript Proxy how to use?

Do you know how to use getters and setters in 👉 JS?

👉 In-depth understanding of ES6 arrow objects

👉 JS decorator pattern instance analysis