search
HomeWeb Front-endVue.jsHow to customize Hooks in Vue3

    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
    • 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
        }
    }
    • 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>

    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?
      }
    }

    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)

    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方法
      }  
    }

    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,
      };
    }

    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)

    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方法
      }  
    }

    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)

    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!

    Statement
    This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
    React, Vue, and the Future of Netflix's FrontendReact, Vue, and the Future of Netflix's FrontendApr 12, 2025 am 12:12 AM

    Netflix mainly uses React as the front-end framework, supplemented by Vue for specific functions. 1) React's componentization and virtual DOM improve the performance and development efficiency of Netflix applications. 2) Vue is used in Netflix's internal tools and small projects, and its flexibility and ease of use are key.

    Vue.js in the Frontend: Real-World Applications and ExamplesVue.js in the Frontend: Real-World Applications and ExamplesApr 11, 2025 am 12:12 AM

    Vue.js is a progressive JavaScript framework suitable for building complex user interfaces. 1) Its core concepts include responsive data, componentization and virtual DOM. 2) In practical applications, it can be demonstrated by building Todo applications and integrating VueRouter. 3) When debugging, it is recommended to use VueDevtools and console.log. 4) Performance optimization can be achieved through v-if/v-show, list rendering optimization, asynchronous loading of components, etc.

    Vue.js and React: Understanding the Key DifferencesVue.js and React: Understanding the Key DifferencesApr 10, 2025 am 09:26 AM

    Vue.js is suitable for small to medium-sized projects, while React is more suitable for large and complex applications. 1. Vue.js' responsive system automatically updates the DOM through dependency tracking, making it easy to manage data changes. 2.React adopts a one-way data flow, and data flows from the parent component to the child component, providing a clear data flow and an easy-to-debug structure.

    Vue.js vs. React: Project-Specific ConsiderationsVue.js vs. React: Project-Specific ConsiderationsApr 09, 2025 am 12:01 AM

    Vue.js is suitable for small and medium-sized projects and fast iterations, while React is suitable for large and complex applications. 1) Vue.js is easy to use and is suitable for situations where the team is insufficient or the project scale is small. 2) React has a richer ecosystem and is suitable for projects with high performance and complex functional needs.

    How to jump a tag to vueHow to jump a tag to vueApr 08, 2025 am 09:24 AM

    The methods to implement the jump of a tag in Vue include: using the a tag in the HTML template to specify the href attribute. Use the router-link component of Vue routing. Use this.$router.push() method in JavaScript. Parameters can be passed through the query parameter and routes are configured in the router options for dynamic jumps.

    How to implement component jump for vueHow to implement component jump for vueApr 08, 2025 am 09:21 AM

    There are the following methods to implement component jump in Vue: use router-link and <router-view> components to perform hyperlink jump, and specify the :to attribute as the target path. Use the <router-view> component directly to display the currently routed rendered components. Use the router.push() and router.replace() methods for programmatic navigation. The former saves history and the latter replaces the current route without leaving records.

    How to jump to the div of vueHow to jump to the div of vueApr 08, 2025 am 09:18 AM

    There are two ways to jump div elements in Vue: use Vue Router and add router-link component. Add the @click event listener and call this.$router.push() method to jump.

    How to transfer value by jumping vueHow to transfer value by jumping vueApr 08, 2025 am 09:15 AM

    There are two main ways to pass data in Vue: props: one-way data binding, passing data from the parent component to the child component. Events: Pass data between components using events and custom events.

    See all articles

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    AI Hentai Generator

    AI Hentai Generator

    Generate AI Hentai for free.

    Hot Article

    R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
    3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. Best Graphic Settings
    3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. How to Fix Audio if You Can't Hear Anyone
    3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
    WWE 2K25: How To Unlock Everything In MyRise
    4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

    Hot Tools

    SublimeText3 Mac version

    SublimeText3 Mac version

    God-level code editing software (SublimeText3)

    DVWA

    DVWA

    Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

    SublimeText3 Chinese version

    SublimeText3 Chinese version

    Chinese version, very easy to use

    mPDF

    mPDF

    mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

    EditPlus Chinese cracked version

    EditPlus Chinese cracked version

    Small size, syntax highlighting, does not support code prompt function