In-depth analysis: using custom Hooks in vue3

What are Hooks

The Hooks technology was first proposed by Sophie Alpert and Dan Abramov of the React team in 2018. It was originally proposed to solve the problem of state logic reuse in React class components. When React uses class components, in order to reuse state logic, it is necessary to use high-level components or Render Props, which will increase the complexity of the code and the maintenance cost. The Hooks technology is a technology that uses specific functions to "hook" React's state and life cycle and other characteristics. It allows us to use state and other React features in function components, replacing traditional class components or higher-order components.

Vue 3.0 does not directly introduce the same concept as React Hooks. Although Vue 3.0 introduces an API similar to Hooks called Composition API, the concepts of the two are slightly different. The Composition API aims to provide better code organization and a way to reuse logic. It is a set of APIs that make it easier to use logic-based composition in Vue 3 applications, and try to solve some of the limitations encountered when using the Options API. and defects.

Although the use of Hooks technology is not mentioned in the official documentation of vue3, we can always see the shadow of Hooks in the Composition API in vue3. For example, onMounted, onUpdated, onUnmounted in vue3 can all be regarded as Hooks. These Hooks can help us access Vue's lifecycle and state methods in function components.

How to customize Hooks

Custom Hooks are a pattern for handling component logic. It allows us to reuse state logic without copy-pasting code between components. Custom hooks are simple JavaScript functions, but when using them, we have to follow two important (unwritten) naming conventions:

  1. They start with use.
  2. They can call other hooks.

If the code we write conforms to these two conventions, then we can write our own hook and use it in Vue components. Generally, we will create a new hooks folder under the src folder to uniformly store the hooks code used in the program.

Let's write a simple hooks with an example below. After we create a new hooks folder under the src folder, we create a new useCounter.js file in it. The code is as follows:

import {
    
     reactive,toRefs } from "vue";
export default function useCounter() {
    
    
  const state = reactive({
    
    
    count:0
  })
  function increment() {
    
    
    state.count++
  }
  return {
    
    
    ...toRefs(state),
    increment
  }
} 

This code defines a file named useCounter.js as a custom hook, which uses reactive to create a responsive state object, and returns an object containing a count property and an increment method.

Below we introduce useCounter in the Vue component, and then call it in the setup function:

<template>
  {
    
    {
    
     count }}
  <button @click="increment">add</button>
</template>

<script setup>
import useCounter from './hooks/useCounter';
const {
    
     count,increment } = useCounter()
</script>

<style scoped>
</style>

In the above code, we introduce the above-defined hook function useCounter in App.vue, deconstruct the count and increment inside, and then use it directly in the template. You can see that this way of using hooks can make the code very concise.

How to write custom Hooks

In fact, in the above introduction of what is custom Hooks , we have already written a custom Hooks. Writing a custom hook is simply to define a reusable js code fragment that is exposed to us, as long as the code logic inside is correct. , we can name this piece of code arbitrarily, but in order to maintain the readability of the code, when we define the Hooks code snippet, we still have to follow the above two industry default naming conventions, namely:

  1. They start with use.
  2. They can call other hooks.

Let's take a hook for showing and hiding the modal box as an example, let's write a custom Hooks

Create a new useModal.js file in the hooks folder, and write the code as follows:

	import {
    
     ref } from "vue"
	
	export default function useModal() {
    
    
	  const isModalVisible = ref(false)
	  const toggleModal = () => {
    
    
	    isModalVisible.value = !isModalVisible.value
	  }	
	  return {
    
     isModalVisible, toggleModal }
	}

So we have written custom Hooks

How to use custom Hooks

Using custom Hooks is also very simple. We only need to use import to import the Hooks code we created in the components that need to use custom Hooks, and then call the properties and methods inside.

As above we defined a hook to show and hide the modal box, we can directly import and use it in the App.vue component, the code is as follows:

<template>
  {
    
    {
    
     count }}
  <button @click="increment">add</button>
  <br>
  {
    
    {
    
     isModalVisible }}
  <button @click="toggleModal">changeModel</button>
</template>

<script setup>
import useCounter from './hooks/useCounter';
import useModal from './hooks/useModal'
const {
    
     count,increment } = useCounter()
const {
    
     isModalVisible, toggleModal } = useModal()
</script>

<style scoped>
</style>

Using Hooks in complex scenarios

In practical applications, the use of custom hooks will be more complicated than our above examples. Common usage scenarios include processing network requests and state management. We also mentioned earlier that in order to better maintain the code, we created a hooks folder for the Hooks code fragment. In Vue3, in order to better maintain the state of the application, the official also recommends that we keep the state as much as possible Separate the hooks and logic into a single aspect, and organize a hooks file separately to store reusable business logic in the entire application or a module.

Next, let's implement a Hooks that registers specific native events

When we deal with complex business logic, sometimes we need to use a specific native event, such as: scroll, resize, etc. We can encapsulate these public native event processing logic into a custom hooks and bind it to a specific property of the component.

For example, if we have a need to monitor the scrollTop value when the mouse scrolls on multiple pages, we can create a new useScroll.js in the hooks folder and write the following code:

import {
    
     ref,onMounted,onUnmounted} from 'vue'

export default function useScroll() {
    
    
  const scrollTop = ref(0)

  const handleScroll = (e) => {
    
    
    console.log(e);
    scrollTop.value = e.target.documentElement.scrollTop
  }

  onMounted(() => {
    
     
    window.addEventListener('scroll', handleScroll)
  })

  onUnmounted(() => {
    
    
    window.removeEventListener('scroll', handleScroll)
  })

  return {
    
    
    scrollTop
  }
}

Then, introduce useScroll.js into the component that we need to obtain the scrollTop value, obtain scrollTop and process related business, here I directly obtain scrollTop in App.vue and display it on the page, the code is as follows:

<template>
  {
    
    {
    
     count }}
  <button @click="increment">add</button>
  <br>
  {
    
    {
    
     isModalVisible }}
  <button @click="toggleModal">changeModel</button>
  <br>
  <br>
  <div>
    {
    
    {
    
     scrollTop }}
  </div>
 
</template>
<script setup>
import useCounter from './hooks/useCounter';
import useModal from './hooks/useModal'
import useScroll from './hooks/useScroll'
const {
    
     count,increment } = useCounter()
const {
    
     isModalVisible, toggleModal } = useModal()
const {
    
     scrollTop }  = useScroll()
console.log(scrollTop);
</script>
<style scoped>
div {
    
    
  height: 900px;
  scroll-margin-top: 10px;
}
</style>

Advantages of using Hooks

  1. Improve the readability and maintainability of component code.
  2. Simplify code logic and reduce code complexity.
  3. Eliminate the use of traditional higher-order component patterns such as "render properties" or "render components".
  4. Encapsulates logic, making components more amenable to reuse.
  5. Using Hook, you don't need to write class components, you can better use JavaScript's functional style and improve code scalability.

In short, custom hooks can not only optimize the code structure of the application, improve code readability, but also enhance the maintainability and scalability of the application. In the actual development of Vue3 components, we should use custom hooks more actively to better meet business needs while improving code quality and performance.

Well, about how to use custom Hooks in vue3, let’s talk about it here today. Before you know it, it’s already 2 o’clock, and you’re going to sleep. If you like it, click on your little hand that makes you rich. Like, follow and add to favorites!

Guess you like

Origin blog.csdn.net/w137160164/article/details/131149050