Home > Web Front-end > Vue.js > How to customize Hooks in Vue3

How to customize Hooks in Vue3

WBOY
Release: 2023-05-11 18:22:13
forward
1548 people have browsed it

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

    Description: If the Composition Api is used under a component with complex functions and a huge amount of code , we work with custom Hooks to write the code in functional blocks, and variables and methods are defined and called together. For example, responsive variables and methods are integrated under function A. For later maintenance, we only need to change the code under function module A. Like Vue2 in Option Api, you need to pay attention to logically dispersed methods and data at the same time.

    So writing custom Hooks in Vue3 must be mastered! It all embodies 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 large number of custom Hooks!

    Define Vue3’s custom Hooks:

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

    Extract in the form of functions Some reusable methods are hung like hooks and can be introduced and called at any time to achieve the goal of high cohesion and low coupling;

    • Extract reusable functions into external JS File

    • Function name/file name starts with use, in the form: useXX

    • Explicitly deconstruct and expose reactive variables or methods when citing It comes out like: const {nameRef, Fn} = useXX()

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

    Example:

    Simple addition and subtraction calculation, separate addition and subtraction into 2 custom Hooks, and transfer 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
    Copy after login
    • Subtraction function-Hook

    //减法功能-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
        }
    }
    Copy after login
    • Addition and subtraction calculation component

    <template>
        <div>
            num1:<input v-model.number="num1"  />
            <br />
            num2:<input v-model.number="num2"  />
        </div>
        <span>加法等于:{{ addNum }}</span>
        <br />
        <span>减法等于:{{ subNum }}</span>
    </template>
    
    <script setup>
    import { ref } from &#39;vue&#39;
    import useAdd from &#39;./useAdd.js&#39;     //引入自动hook 
    import { useSub } from &#39;./useSub.js&#39; //引入自动hook 
    
    const num1 = ref(2)
    const num2 = ref(1)
    //加法功能-自定义Hook(将响应式变量或者方法形式暴露出来)
    const { addNum, addFn } = useAdd({ num1, num2 })
    addFn(num1.value, num2.value)
    //减法功能-自定义Hook (将响应式变量或者方法形式暴露出来)
    const { subNum, subFn } = useSub({ num1, num2 })
    subFn(num1.value, num2.value)
    </script>
    Copy after login

    The relationship between Vue3 custom Hooks and Mixin in the Vue2 era:

    Insufficient Mixin

    In Vue 2, mixin abstracts some component logic into reusable blocks main tool. However, they have several problems:

    1. Mixins are prone to conflicts: because the properties of each mixin are merged into the same component, in order to avoid property name conflicts, you still need to understand each other characteristics.

    2. Reusability is limited: we cannot pass any parameters to the mixin to change its logic, which reduces their flexibility in abstract logic.

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

    1. Mixin methods and attributes that are difficult to trace

    Vue3 custom Hooks can

    Vue3 custom Hooks, explicitly expose responsive variables or methods when referencing, such as:

    const {nameRef, Fn} = useXX()

    Mixins

    export default {
      mixins: [ a, b, c, d, e, f, g ], //一个组件内可以混入各种功能的Mixin
      mounted() {
        console.log(this.name)  //问题来了,这个name是来自于哪个mixin?
      }
    }
    Copy after login

    Unknown Mixin confusion, we simply cannot know which Mixin file the attributes come from, which brings difficulties to later maintenance

    Vue3 Custom Hooks

    //加法功能-自定义Hook(将响应式变量或者方法形式暴露出来)
    const { addNum, addFn } = useAdd({ num1, num2 })
    addFn(num1.value, num2.value)
    //减法功能-自定义Hook (将响应式变量或者方法形式暴露出来)
    const { subNum, subFn } = useSub({ num1, num2 })
    subFn(num1.value, num2.value)
    Copy after login

    us It is easy to see the responsive variables and methods explicitly exposed by each Hook

    2. You cannot 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. Parameters are not limited to variables exposed by other hooks.

    Mixins

    export default {
      mixins: [ addMixin, subMixin], //组件内混入加法和减法Mixin
      mounted(){
          this.add(num1,num2) //调用addMixin内部的add方法
          this.sub(num1,num2) //调用subMixin内部的sub方法
      }  
    }
    Copy after login

    can be passed by calling Mixin internal methods. Parameters, but cannot directly pass parameters to Mixin, because Mixin is not exposed in function form and does not pass parameters

    Vue3 custom Hook

    Add an average Hook# based on the above example ##

    //平均功能-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,
      };
    }
    Copy after login

    Inside the component

    //组件内
    //加法功能-自定义Hook(将响应式变量或者方法形式暴露出来)
    const { addNum, addFn } = useAdd({ num1, num2 })
    addFn(num1.value, num2.value)//主动调用,返回最新addNum
    //平均功能-自定义Hook- hook传入参数值来其他hook暴露出来的变量
    const { averageNum, averageFn} = useAverage(addNum)
    averageFn(addNum.value)
    Copy after login

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

    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], //组件内混入加法和减法Mixin
      mounted(){
          this.add(num1,num2) //调用加法addMixin内部的add方法
          this.sub(num1,num2) //调用减法subMixin内部的sub方法
      }  
    }
    Copy after login

    If this The variable totalNum with the same name returned by the calculation results of .add(num1,num2) and this.sub(num1,num2), due to JS single thread, the later introduced ones will overwrite the previous ones, totalNum is ultimately the value of subtraction sub

    Vue3 Custom Hooks

    //加法功能-自定义Hook(将响应式变量或者方法形式暴露出来)
    const { totalNum:addNum, addFn } = useAdd({ num1, num2 })
    addFn(num1.value, num2.value)
    //减法功能-自定义Hook (将响应式变量或者方法形式暴露出来)
    const { totalNum:subNum, subFn } = useSub({ num1, num2 })
    subFn(num1.value, num2.value)
    Copy after login
    In Vue3 custom Hooks, although addition and subtraction Hooks both return totalNum, it is easy to rename variables using ES6 object destructuring

    The above is the detailed content of How to customize Hooks in Vue3. For more information, please follow other related articles on the PHP Chinese website!

    Related labels:
    source:yisu.com
    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
    Popular Tutorials
    More>
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template