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
    Vue.js vs. React: Scalability and MaintainabilityVue.js vs. React: Scalability and MaintainabilityMay 10, 2025 am 12:24 AM

    Vue.js and React each have their own advantages in scalability and maintainability. 1) Vue.js is easy to use and is suitable for small projects. The Composition API improves the maintainability of large projects. 2) React is suitable for large and complex projects, with Hooks and virtual DOM improving performance and maintainability, but the learning curve is steeper.

    The Future of Vue.js and React: Trends and PredictionsThe Future of Vue.js and React: Trends and PredictionsMay 09, 2025 am 12:12 AM

    The future trends and forecasts of Vue.js and React are: 1) Vue.js will be widely used in enterprise-level applications and have made breakthroughs in server-side rendering and static site generation; 2) React will innovate in server components and data acquisition, and further optimize the concurrency model.

    Netflix's Frontend: A Deep Dive into Its Technology StackNetflix's Frontend: A Deep Dive into Its Technology StackMay 08, 2025 am 12:11 AM

    Netflix's front-end technology stack is mainly based on React and Redux. 1.React is used to build high-performance single-page applications, and improves code reusability and maintenance through component development. 2. Redux is used for state management to ensure that state changes are predictable and traceable. 3. The toolchain includes Webpack, Babel, Jest and Enzyme to ensure code quality and performance. 4. Performance optimization is achieved through code segmentation, lazy loading and server-side rendering to improve user experience.

    Vue.js and the Frontend: Building Interactive User InterfacesVue.js and the Frontend: Building Interactive User InterfacesMay 06, 2025 am 12:02 AM

    Vue.js is a progressive framework suitable for building highly interactive user interfaces. Its core functions include responsive systems, component development and routing management. 1) The responsive system realizes data monitoring through Object.defineProperty or Proxy, and automatically updates the interface. 2) Component development allows the interface to be split into reusable modules. 3) VueRouter supports single-page applications to improve user experience.

    What are the disadvantages of VueJs?What are the disadvantages of VueJs?May 05, 2025 am 12:06 AM

    The main disadvantages of Vue.js include: 1. The ecosystem is relatively new, and third-party libraries and tools are not as rich as other frameworks; 2. The learning curve becomes steep in complex functions; 3. Community support and resources are not as extensive as React and Angular; 4. Performance problems may be encountered in large applications; 5. Version upgrades and compatibility challenges are greater.

    Netflix: Unveiling Its Frontend FrameworksNetflix: Unveiling Its Frontend FrameworksMay 04, 2025 am 12:16 AM

    Netflix uses React as its front-end framework. 1.React's component development and virtual DOM mechanism improve performance and development efficiency. 2. Use Webpack and Babel to optimize code construction and deployment. 3. Use code segmentation, server-side rendering and caching strategies for performance optimization.

    Frontend Development with Vue.js: Advantages and TechniquesFrontend Development with Vue.js: Advantages and TechniquesMay 03, 2025 am 12:02 AM

    Reasons for Vue.js' popularity include simplicity and easy learning, flexibility and high performance. 1) Its progressive framework design is suitable for beginners to learn step by step. 2) Component-based development improves code maintainability and team collaboration efficiency. 3) Responsive systems and virtual DOM improve rendering performance.

    Vue.js vs. React: Ease of Use and Learning CurveVue.js vs. React: Ease of Use and Learning CurveMay 02, 2025 am 12:13 AM

    Vue.js is easier to use and has a smooth learning curve, which is suitable for beginners; React has a steeper learning curve, but has strong flexibility, which is suitable for experienced developers. 1.Vue.js is easy to get started with through simple data binding and progressive design. 2.React requires understanding of virtual DOM and JSX, but provides higher flexibility and performance advantages.

    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

    Video Face Swap

    Video Face Swap

    Swap faces in any video effortlessly with our completely free AI face swap tool!

    Hot Article

    Hot Tools

    SublimeText3 English version

    SublimeText3 English version

    Recommended: Win version, supports code prompts!

    Safe Exam Browser

    Safe Exam Browser

    Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

    SecLists

    SecLists

    SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

    Notepad++7.3.1

    Notepad++7.3.1

    Easy-to-use and free code editor

    PhpStorm Mac version

    PhpStorm Mac version

    The latest (2018.2.1) professional PHP integrated development tool