existVue
Among them, a very important function is component reuse, writingVue
Components are more about assembling components to modularize the various functions of the page.
Easy to maintain and manage, while in the project, the logical functions of some components in the page are the same. If the functional logic is not reused, each page needs to be written repeatedly.
existVue
Each component remains independent.If you want to reuse the logic of a component in the page, that is, the code that reuses the logic of the component
SoIt can be separated from logic and placed in a public place for management, which is convenient for calling in other places, achieving the purpose of reusing code and logic.
existVue2
Can be usedmixin
, but there are many disadvantages to using this, and inVue3
Combination functions are introduced, that is, customhooks
It solved the previous problem very well
Custom hooks
explain: Essentially a function,setup
Used in the functioncomposition API
Encapsulated and multiplexed functions with stateful logic
similarVue2
ofmixin
Advantages: Customhooks
, reuse code, letsetup
The logic in it is clearer and easier to understand
Click the screen to record the mouse position
There is now a requirement: it is to record the location where the user clicks on the browser, display it on the browser, and use a combined API in the component to realize the click-and-mouse tracking function. The sample code is as follows
Create a new one
import { ref,onMounted,onUnmounted } from 'vue'; const x = ref(0); // The value of coordinate xconst y = ref(0); // The value of coordinate y function update(event) { = ; = ; } onMounted(() => { /* ('click',(event) => { = ; = ; })*/ ('click',update) // For the subsequent callback processing function, it can be extracted separately }) // Side effects of unbinding functiononUnmounted(() => { ('click',update); })
Template code
<template>The mouse position is:{{x}},{{y}}</template>
Now, if you want to reuse this same functional logic in multiple components, we can extract this logic into an external file in the form of a combined function. We name this file.
import {ref,onMounted,onUnmounted} from 'vue'; // According to custom, the combination function name begins with `use`export function usePoint() { // The state encapsulated and managed by a combined function const x = ref(0); const y = ref(y); function update(event) { = ; = ; } onMounted(() => { ('click',update) }) // Side effects of unbinding function onUnmounted(() => { ('click',update); }) //Expose all managed status through return value return { x, y } }
That's how it is used in components
<script setup> import { usePoint } from "./" const { x,y} = usePoint(); // If you want to use the returned state in the combined function in the form of object properties, you can wrap the returned object with reactive() once, so that the ref in it will be automatically unpacked const clickPoint = reactive(usePoint()); // Link to the original x ref (,); </script>
Then in the template
<template> Mouse coordinates: {{x}},{{y}} or Mouse coordinates: {{}},{{}} </template>
The core logic is exactly the same. All we do is move it into an external function and return the state that needs to be exposed. Like in components, you can also use all combos in combosAPI
. Now,usePoint()
The functions can be easily reused in any component.
Multiple combination functions can be nested: a combination function can call one or more other combination functions. This allows us to combine multiple smaller and logically independent units to form complex logic just like we combine multiple components into the entire application. In fact, this is also the design patternAPI
Name the set as a combination API
Naming hooks function
Combination function convention is named by camel anduse
As the beginning
Comparison with Mixin
Vue2
Probably correctmixins
More familiar options. It also allows us to extract component logic into reusable units. Howevermixins
There are three main shortcomings:
[1]. Unclear data source: When multiple data are usedmixin
When, which data attributes on the instance come frommixin
Becoming unclear, this makes it difficult to trace back implementation and understand component behavior. This is also recommended in combination functionsref
+Reason for deconstructing the pattern: Let the source of the attribute be clear at a glance
[2]. Namespace conflict: multiple from different authorsmixin
The same attribute name may be registered, causing naming conflicts. If you use a combination function, you can avoid the same key names by renaming the variable when deconstructing it.
[3]. Implicit crossmixin
Communication: Multiplemixin
Relying on shared attribute names is required to interact, which makes them implicitly coupled together. The return value of a combined function can be passed in as a parameter of another combined function, like a normal function
existVue 3
Not recommended for use in mixin
. Sometimes you need to find a variable, then you need a global search
Comparison with renderless components
The main advantage of a combined function over a render-free component is that a combined function does not incur additional component instance overhead. When used throughout the application, additional component instances generated by renderless components can bring unignorable performance overhead.
We recommend using a combination function when pure logic multiplexing, and using a renderless component when you need to reuse both logic and view layouts simultaneously.
Summarize
Combined API functions, extracting combined functions is not only for reuse, but also for code organization. Combined APIs will give you more flexibility, allowing you to split component code into smaller functions based on logical problems.
For management, in short, vue3's custom hooks function is very practical for the logical code of multiplexed components
This is the end of this article about how to customize hooks (combination) functions in Vue. For more related content of custom hooks functions, please search for my previous articles or continue browsing the following related articles. I hope everyone will support me in the future!