This is the 19th day of my participation in the More text Challenge. For details, see more text Challenge

The use of the ref function

The ref() function converts data into reactive data and is typically used to define reactive data of a basic type.

1.1 Creating a REF Route

Write your own vuE3 template page is too troublesome, VSCode custom code snippets, search vue

And then I’m going to fill in the code

"vue3": {
		"prefix": "vue3"."body": [
			"<template>"." 
      
"
.""." "."</template>".""."<script lang=\"ts\">"."import { defineComponent } from 'vue';".""."export default defineComponent({"." name: '',"."});"."</script>".""."<style scoped>".""."</style>"]."description": "Vue3 initialization" } Copy the code

Then click vsCode to generate the VUe3 template

Vue = home/vue = home/vue = home/vue = home/vue = home/vue = home/vue = home/vue

 <button @click="goPage('/ref')"</button id >import { useRouter } from 'vue-router';
 let router = useRouter()
 let goPage = (path:string) = > {
      router.push(path)
    }
Copy the code

Ref. Vue

<template>
  <div>
      {{count}} <button @click="incrementCount">+</button>
  </div>
</template>

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

export default defineComponent({
  name: ' '.setup() {
      let count = 0
      let incrementCount = () = > {
          count++
          console.log(count);
      }
      return {
          count,
          incrementCount,
      }
  }
});
</script>

<style scoped>

</style>
Copy the code

You can see that the ref is not used, the data is incrementing, but the view is unchanged

With the REF, the data is bidirectional

 let count =ref(0) 
      let incrementCount = () = > {
          count.value++
          console.log(count.value);
      }
Copy the code

Use of reactive functions

The reactive () function, similar to the ref () function, makes the data reactive and automatically updates the template view when the data changes. The difference is that ref () is used for base data types, while reactive () is used for reference data types, such as objects or arrays.

For example, add a user list

Reactive, not reactive

<template>
  <div>
      <ul>
          <li v-for="(item,index) in userList" :key="index">{{item.name}}</li>
      </ul>
      <button @click="addUser">Add user</button>
  </div>
</template>

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

export default defineComponent({
  name: "reactive".setup() {
    let userList = [
      {
        id: 1.name: "Zhang"}, {id: 2.name: "Bill"}, {id: 3.name: "Fifty",},];let addUser = () = > {
        let user = {
            id: userList.length + 1.name: 'Robot' + userList.length + 1
        }
        userList.push(user)
        console.log(userList);
        
    }
    return {
        userList,
        addUser
    }
  },
});
</script>

<style scoped>
</style>
Copy the code

Reactive data becomes a proxy. Reactive data becomes reactive

import { defineComponent,reactive } from "vue";
 let userList = reactive([
      {
        id: 1.name: "Zhang"}, {id: 2.name: "Bill"}, {id: 3.name: "Fifty",}]);Copy the code

Push is ok, because the underlying layer will determine whether it is the basic data type or the reference data type. If it is the reference data type, it will still use the method of reactive. Therefore, reactive is recommended by the official

Three, the principle of response

The responsive principle of Vue3 is that proxy is used to read, write, add and delete the object attribute value to hijack, and Reflect is used to dynamically perform specific operations on the properties of the object being represented. Since Proxy and Reflect do not support IE browser, This is one of the main reasons why Vue3 does not support Internet Explorer. I’m gonna create a new HTML

<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta Name ="viewport" content="width=device-width, initial =1.0"> <title>Document</title> <script> let user = {id: } let proxyUser = new Proxy(user,{target,prop) {console.log(target,prop); } }) proxyUser.name </script> </head> <body> </body> </html>Copy the code

Get the value inside

 let proxyUser = new Proxy(user,{
            get(target,prop) {
                console.log(target,prop);
                return target[prop]
            }
        })
        let result = proxyUser.name
        console.log(result,'Attribute value');
Copy the code

Optimization: Use Reflect to get the value

 get(target,prop) {
                console.log(target,prop);
                // return target[prop]
                return Reflect.get(target,prop)
            }
Copy the code

Use set to set the value

  / / set the value
            set(targe,prop,val) {
                // targe[prop] = val
                Reflect.set(targe,prop,val)
            }
            
            
        let result = proxyUser.name
        console.log(result,'Attribute value original');
        proxyUser.name = 'bill'
        let result2 = proxyUser.name
        console.log(result2,'Attribute value changed');
        console.log(user,'Proxied object');
Copy the code

The object being proxied has also changed.

Delete the value

  / / delete values
            deleteProperty(target,prop) {
                // Delete target[prop] // Not recommended
                Reflect.deleteProperty(target,prop)
            }
            
    delete proxyUser.name
        console.log(user,'Deleted proxied objects');
Copy the code

The complete code

<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta Name ="viewport" content="width=device-width, initial =1.0"> <title>Document</title> <script> let user = {id: } let proxyUser = new Proxy(user,{// get(target,prop) {console.log(target,prop); // return target[prop] return Reflect.get(target,prop) }, Set (targe,prop,val) {// reflect.set (targe,prop,val)}, DeleteProperty (target,prop) {// delete target[prop] // Not recommended reflect.deleteProperty (target,prop)}}) Let result = Proxyuser.name console.log(result,' attribute value original '); Let result2 = proxyuser.name console.log(result2,' attribute value changed '); Console. log(user,' proxied object '); Delete proxyuser.name console.log(user,' deleted proxyuser.name '); </script> </head> <body> </body> </html>Copy the code