This is the 22nd day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021

Hooks:

  1. What are hooks? ———— is essentially a function that encapsulates the positionAPI used in the Setup function

  2. Similar to mixins in vue2. X

  3. The advantage of custom hooks: Reusing code to make logic in SETUP clearer and easier to understand

import { reactive, onMounted, onBeforeUnmount } from 'vue'
setup() {
        let point = reactive({
            x: 0.y: 0
        })
        function usePoint(event) {
            point.x = event.x
            point.y = event.y
        }
        onMounted(() = > {
            window.addEventListener('click', usePoint)
        })
        onBeforeUnmount(() = > {
            window.removeEventListener('click', usePoint)
        })

        return {
            point
        }
 }
Copy the code

We wrapped this part of the code into a JS file, as follows:

For example, create a new hooks folder in the root directory and add the usepoint. js file to this folder, move all the functional code to this js folder as follows:

At this point, we have a package of functional hooks, similar to the mixins of vue2.x

ToRef/toRefs:

  • Creates a ref object whose value points to an attribute in another object

  • Const name = toRef(person,’name’)

  • Application: To provide a property in a reactive object for external use alone

  • ToRefs (person) toRefs(person) toRefs(person) toRefs(person)

Example: Let’s start by defining an object reactive:

The interface effect is as follows:

As you can see at this point, we’re getting a little cumbersome with the tag, and we’re going to have to write the person multiple times, so let’s see if we can change it to something like this:

After the modification, the interface effect is the same as the original, but when we click the button, we will find that there is no response, why is this, in fact, the above writing is equivalent to

return {
    name:'liudan'.age:18.salary:70
}
Copy the code

Therefore, we can use toRef or toRefs to achieve the effect of the previous response, as follows:

ToRef writing:

Let’s print this name:

You can see that it’s an ObjectRefImpl object with get and set methods in it, and the value reads the name value of the Person object, which is reactive

The above code can also be abbreviated as:

return {
    name:toRef(person,'name')... }Copy the code

toRefs

    const x = toRefs(person)
    console.log(x)
Copy the code

As you can see, toRefs converts all of the attributes in Person into responsive data at once, which is handy and easy to use. The final code can be written like this: