Vue3 must know skills - custom Hooks

Vue3 custom Hooks definition:

Personal understanding: some reusable methods hang like hooks and can be introduced and called at any time to achieve the goal of high cohesion and low coupling, and they should all be considered hooks;

Why does Vue3 use custom Hook? :

Conclusion: It is to make the Composition Api more useful and fuller, and to make writing Vue3 more enjoyable! Write code like poetry!
In fact, the deeper meaning of this question is why Vue3 is better than Vue2! The performance of no outgoing calls is greatly improved. In fact, the coding experience is also the advantage of Vue3. The introduction of Composition Api (to solve the strong coupling of Option Api in the case of a large amount of code) allows developers to have a better development experience.

Personal thoughts: But these so-called improvement of the development experience all require developers to continuously learn to develop good coding habits. It is also Vue3 to write Composition Api. Some people can write like poems, and some people can write like poems. 💩The same (sincerely hope that every developer has a heart that is passionate about technology, don’t develop for the sake of development, predecessors write and let future generations taste it! Sorry for being too emotional about maintaining old projects recently)

When writing Vue3, please get rid of the idea of ​​Vue2's brainless this:

Many students in writing Vue2 have developed the habit of Option Api without this, and when they come to the Composition Api of Vue3, they still want to use this habitually, and some people even introduce getCurrentInstance in order to write this! This is not necessary!

One of the advantages of Composition Api is to get rid of the strong coupling caused by brainless this. The functions are intermixed with each other, variables and methods are mixed in various methods, and the ubiquitous this is strongly coupled. Although it is convenient, the fragmented option api later Maintenance is troublesome.

I believe that students who write Vue2 must feel deeply. A large number of variables and methods are defined under one component, methods are nested, and methods share variables with each other. To maintain such code, the seemingly easy-to-understand Option Api writing method, we need Switching back and forth between methos, data, and template, Option Api is very simple and clear when the code volume and functions are small, but when the code volume is large, the function is complex, I believe that the review code will have a headache.

On the other hand, in the Composition Api with complex functions and huge amount of code, we cooperate with custom Hooks, write the code in functional blocks, and define and call the response variables and methods together. In this way, we only need to focus on function A when we change function A later. The code under the block will not pay attention to both methods and data like Vue2 in Option Api. . . . .

Let’s review the Composition Api with a few animations!

Thank you Mr. Big Handsome Lao Ape for the animation. The advantages and disadvantages of Composition Api VS Option Api are very clearly displayed on the animation!

It’s good that Option Api has a small amount of code, but a large amount of code can easily lead to high coupling!

Note: The above is the writing method of Vue2 Option Api. One component contains data, methos, computed, and watch. The same function needs to be written separately on these functions. If the amount of code is small, it seems very clear and clear. Once the amount of code is large and the functions are complex, each function is written separately, and data, methos, computed, and watch need to be switched back and forth during maintenance, which is too scattered and highly coupled.

Composition Api decouples Vue2 Option Api to achieve low coupling and high cohesion

Note: If the Composition Api is a component with complex functions and a huge amount of code, we cooperate with custom Hook s to write the code in functional blocks, and define and call variables and methods together. For example, the A function integrates responsive variables and method, we only need to change the code under the A function module in the later maintenance, not like Vue2 in Option Api, which needs to pay attention to the methods and data of scattered logic at the same time.

So custom Hook writing Vue3 must master! It all reflects the idea of ​​low coupling and high cohesion of Vue3 Composition Api! After reading the official documents and open source admin templates, the author uses a lot of custom Hooks!

Boldly define Vue3's custom Hook:

Although the official does not clearly specify or define what custom Hooks are, they are used everywhere;

Extract some reusable methods in the form of functions and hang like hooks, which can be introduced and called at any time to achieve the goal of high cohesion and low coupling;

  1. Extract reusable functions into external JS files

  2. The function name/file name starts with use, such as: useXX

  3. Explicitly destructuring and exposing reactive variables or methods when referencing, such as: const {nameRef, Fn} = useXX()

    (deconstructs the variables and methods of custom hooks in the setup function)

Example:

Simple addition and subtraction calculations, separate addition and subtraction into 2 custom Hooks, and pass responsive data to each other

  • Addition function - Hook
import { ref, watch } from 'vue';
const useAdd= ({ num1, num2 })  =>{
    const addNum = ref(0)
    watch([num1, num2], ([num1, num2]) => {
        addFn(num1, num2)
    })
    const addFn = (num1, num2) => {
        addNum.value = num1 + num2
    }
    return {
        addNum,
        addFn
    }
}
export default useAdd
  • Subtraction Function - Hook
//Subtraction Function - Hook
import { ref, watch } from 'vue';
export function useSub  ({ num1, num2 }){
    const subNum = ref(0)
    watch([num1, num2], ([num1, num2]) => {
        subFn(num1, num2)
    })
    const subFn = (num1, num2) => {
        subNum.value = num1 - num2
    }
    return {
        subNum,
        subFn
    }
}
  • Addition and Subtraction Computation Component
<template>
    <div>
        num1:<input v-model.number="num1" style="width:100px" />
        <br />
        num2:<input v-model.number="num2" style="width:100px" />
    </div>
    <span>addition equals:{{ addNum }}</span>
    <br />
    <span>subtraction equals:{{ subNum }}</span>
</template>
​
<script setup>
import { ref } from 'vue'
import useAdd from './useAdd.js'     //Introduce automatic hook s 
import { useSub } from './useSub.js' //Introduce automatic hook s 
​
const num1 = ref(2)
const num2 = ref(1)
//Addition function - custom Hook (exposing responsive variables or methods)
const { addNum, addFn } = useAdd({ num1, num2 })
addFn(num1.value, num2.value)
//Subtraction function - custom Hook (exposing responsive variables or methods)
const { subNum, subFn } = useSub({ num1, num2 })
subFn(num1.value, num2.value)
</script>
​

Let's talk about the relationship between Vue3 custom Hooks and Vue2 era Mixin through the above example:

Refer to the vue actual combat video explanation: into learning

Mixin insufficient
 exist Vue 2 middle, mixin It is the main tool for abstracting parts of component logic into reusable blocks. However, they have several problems:
1,Mixin Conflicts can easily arise: because each mixin of property are all merged into the same component, so in order to avoid property name clashes, you still need to know about every other feature.
2,Reusability is limited: we cannot mixin Passing any arguments to change its logic makes them less flexible in terms of abstract logic.

The above paragraph is the content of the official documentation of Vue3, which can be summarized and supplemented as:

1. Mixin's methods and properties that are difficult to trace! Vue3 custom Hooks can

Vue3 customizes Hooks, and explicitly exposes reactive variables or methods when referenced, such as:

const {nameRef,Fn} = useXX()

  • Mixins

    export default {
      mixins: [ a, b, c, d, e, f, g ], //A Mixin that can mix various functions into a component
      mounted() {
        console.log(this.name)  //The question is, which mixin does this name come from?
      }
    }
    

    Mixin is unclear and confusing, we can't know which Mixin file the attribute comes from, which brings difficulties to later maintenance

  • Vue3 custom Hooks

    //Addition function - custom Hook (exposing responsive variables or methods)
    const { addNum, addFn } = useAdd({ num1, num2 })
    addFn(num1.value, num2.value)
    //Subtraction function - custom Hook (exposing responsive variables or methods)
    const { subNum, subFn } = useSub({ num1, num2 })
    subFn(num1.value, num2.value)
    

    We can easily see the reactive variables and methods that are explicitly exposed by each Hooks

2. It is not possible to pass parameters to Mixin to change the logic, but Vue3 custom Hooks can:

Vue3 custom Hooks can flexibly pass any parameters to change its logic. The parameters are not limited to the variables exposed by other hook s.

  • Mixins
export default {
  mixins: [ addMixin, subMixin], //Addition and Subtraction Mixin s in Components
  mounted(){
      this.add(num1,num2) //Call the add method inside addMixin
      this.sub(num1,num2) //Call the sub method inside subMixin
  }  
}

You can pass parameters by calling the internal method of Mixin, but you cannot pass parameters directly to Mixin, because Mixin is not exposed in the form of a function, and no parameters are passed.

  • Vue3 custom Hook

    Add an average Hook based on the above example

    //Average Function - Hook
    import { ref, watch } from "vue";
    export function useAverage(addNum) {
      const averageNum = ref(0);
      watch(addNum, (addNum) => {
        averageFn(addNum);
      });
      const averageFn = (addNum) => {
        averageNum.value = addNum / 2;
      };
      return {
        averageNum,
        averageFn,
      };
    }
    

    inside the component

    //inside the component
    //Addition function - custom Hook (exposing responsive variables or methods)
    const { addNum, addFn } = useAdd({ num1, num2 })
    addFn(num1.value, num2.value)//Active call, return the latest addNum
    //Average function-custom Hook- hook passes in parameter values ​​to variables exposed by other hooks
    const { averageNum, averageFn} = useAverage(addNum)
    averageFn(addNum.value)
    

    Vue3 custom Hooks can flexibly pass any parameters to change its logic. The parameters are not limited to the exposed variables of other hook s, which improves the flexibility of Vue3 in abstract logic.

3. Mixin variables with the same name will be overwritten. Vue3 custom Hook can rename variables with the same name when introduced.

  • Mixins

    export default {
      mixins: [ addMixin, subMixin], //Addition and Subtraction Mixin s in Components
      mounted(){
          this.add(num1,num2) //Call the add method inside the addition addMixin
          this.sub(num1,num2) //Call the sub method inside the subtraction subMixin
      }  
    }
    

    If the results of this.add(num1,num2) and this.sub(num1,num2) return the variable totalNum of the same name, due to the single thread of JS, the one introduced later will overwrite the previous one, and totalNum will eventually be the value of the subtraction sub

  • Vue3 custom Hooks

    //Addition function - custom Hook (exposing responsive variables or methods)
    const { totalNum:addNum, addFn } = useAdd({ num1, num2 })
    addFn(num1.value, num2.value)
    //Subtraction function - custom Hook (exposing responsive variables or methods)
    const { totalNum:subNum, subFn } = useSub({ num1, num2 })
    subFn(num1.value, num2.value)
    

    In Vue3 custom Hooks, although both addition and subtraction Hooks return totalNum, it is easy to rename variables using ES6 object destructuring

Summarize:

In the Vue2 era, Option Api, data, methos, watch... are written separately. This is fragmented and scattered. Once the code is too much, it is easy to be highly coupled, and it is tedious to switch the code back and forth during maintenance!

Composition Api in the Vue3 era, by using various Hooks and custom Hooks to write fragmented responsive variables and methods into functional blocks to achieve high cohesion and low coupling

Visually speaking: Vue3 custom Hooks are function scopes under components, while Mixins in Vue2 era are global scopes under components. The global scope is sometimes uncontrollable. Just like the variable declaration keywords var and let, const and let are modifications of var. Composition Api is a correction to the high coupling of Option Api in the Vue2 era and the black box of this everywhere, and Vue3 custom Hooks is an improvement.

Compare Mixin with custom Hook, one is the embodiment of Option Api, the other is the embodiment of Composition Api. If you can understand the idea of ​​high cohesion and low coupling, then you can understand why Vue3 uses Composition Api and makes the code stronger through various custom Hooks. Write code like poetry. instead of writing shit.

Tags: Vue

Posted by NiXXeD on Mon, 07 Nov 2022 10:37:48 +0300