SoFunction
Updated on 2025-04-05

VUE3 encapsulation of a Hook implementation example

In Vue 3,Composition APIAllows us to encapsulate and reuse code logic, especially throughsetupFunctions are used to reuse between components. To improve code reusability, we can encapsulate some common API request and state management logic into a separatehookmiddle.

Here is a simple example where we will encapsulate an API request for fetching user data and provide logic for handling the status, errors, and data of the request:

Example: Encapsulation API Request Hook

// 
import { ref } from 'vue'
import { getUserData } from '@/api/user'  // Assume this is the API request you defined
export function useUserData() {
  const userData = ref(null)  //Storing user data  const isLoading = ref(false)  // Request load status  const error = ref(null)  // error message
  // Function to obtain user data  const fetchUserData = async () => {
     = true
     = null
    try {
      const response = await getUserData()  // Assume this is an API request that returns user data       = 
    } catch (err) {
       =  || 'Failed to get data'
    } finally {
       = false
    }
  }

  // Return to status and operation  return {
    userData,
    isLoading,
    error,
    fetchUserData,
  }
}

Use this Hook in the component

// 
<template>
  <div>
    <button @click="fetchUserData" :disabled="isLoading">
      Get user data
    </button>

    <div v-if="isLoading">loading...</div>
    <div v-if="error">{{ error }}</div>
    <div v-if="userData">
      <p>username:{{  }}</p>
      <p>age:{{  }}</p>
      <!-- More user information display -->
    </div>
  </div>
</template>

<script lang="ts" setup>
import { useUserData } from '@/hooks/useUserData'  // Introduce packaged Hook
// Use Hookconst { userData, isLoading, error, fetchUserData } = useUserData()

// Triggers to get user data when component loadsonMounted(() => {
  fetchUserData()
})
</script>

optimization:

Encapsulate API request logic and state management intouseUserDataIn  , you can easily reuse this logic in different components, just import and calluseUserDataJust do it. In this way, the logic of the component is more concise, and the API request logic can also be centrally managed, enhancing the maintainability and reusability of the code.

For example:

Suppose you have multiple pages or components that need to make user data requests, you only need to call them in these components.useUserDatawithout repeatedly writing the same request and state management logic.

Another component reuse

// 
<template>
  <div>
    <h3>User Details</h3>
    <button @click="fetchUserData" :disabled="isLoading">
      Get user data
    </button>

    <div v-if="isLoading">loading...</div>
    <div v-if="error">{{ error }}</div>
    <div v-if="userData">
      <p>username:{{  }}</p>
      <p>e-mail:{{  }}</p>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { useUserData } from '@/hooks/useUserData'

const { userData, isLoading, error, fetchUserData } = useUserData()

onMounted(() => {
  fetchUserData()
})
</script>

Through this encapsulation, API requests and related state management are effectively abstracted. Each component that needs to obtain user data is simply calleduseUserData, making the code more concise, maintainable and easy to reuse.

This is the end of this article about the implementation example of VUE3 encapsulation of a Hook. For more related content on VUE3 encapsulation of a Hook, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!