【Vue 3】如何封装一个超级好用的 Hook!

简介: 【Vue 3】如何封装一个超级好用的 Hook!

在 Vue 3 中,组合式 API 的出现给我们带来了很多新的编程方式和思路。

其中,Hook 是一种非常强大的工具,可以帮助我们更好地复用代码,提升开发效率。

在这篇文章中,我将详细介绍什么是 Hook,以及如何在 Vue 3 中封装一个超级好用的 Hook。

我们将通过多个实例,逐步深入探讨 Hook 的封装技巧和使用场景。

什么是 Hook

Hook 是一种将逻辑复用的方式,可以帮助我们将组件中的逻辑提取出来,形成独立的函数。

在 Vue 3 中,Hook 通常是指使用 setup 函数中的组合式 API 封装的逻辑函数。

通过 Hook,我们可以在多个组件中复用相同的逻辑,而不需要重复编写代码。

在 Vue 中使用 Hook

在 Vue 3 中,使用 Hook 非常简单。

我们可以通过在 setup 函数中定义一个函数,然后在需要的地方调用这个函数来实现逻辑复用。

下面是一个简单的示例:

<!-- src/components/ExampleComponent.vue -->
<template>
  <div class="example">
    <h1>{{ message }}</h1>
  </div>
</template>
<script setup>
import { ref }from'vue'
functionuseExample(){
const message =ref('Hello, Vue 3 Hook!')
return{ message }
}
const{ message }=useExample()
</script>
<style scoped>
.example {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  text-align: center;
  margin-top: 60px;
}
</style>

封装表格 Hook

我们经常需要在多个地方使用表格组件,并且每个表格都有类似的逻辑,比如数据获取、分页、排序等。

为了避免代码重复,我们可以封装一个表格 Hook 来复用这些逻辑。

如何封装

首先,我们创建一个名为 useTable.js 的文件:

// src/hooks/useTable.js
import{ ref }from'vue'
import axios from'axios'
exportfunctionuseTable(url){
const data =ref([])
const loading =ref(false)
const currentPage =ref(1)
const total =ref(0)
constfetchData=async()=>{
    loading.value=true
try{
const response =await axios.get(url,{
params:{
page: currentPage.value,
},
})
      data.value= response.data.items
      total.value= response.data.total
}catch(error){
console.error('Error fetching data:', error)
}finally{
      loading.value=false
}
}
fetchData()
return{ data, loading, currentPage, total, fetchData }
}

然后,我们在组件中使用这个 Hook:

<!-- src/components/TableComponent.vue -->
<template>
<div class="table-component">
<table v-if="!loading">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr v-for="item in data" :key="item.id">
<td>{{ item.id }}</td>
<td>{{ item.name }}</td>
</tr>
</tbody>
</table>
<p v-else>Loading...</p>
<button @click="prevPage" :disabled="currentPage === 1">Previous</button>
<button @click="nextPage" :disabled="currentPage === total">Next</button>
</div>
</template>
<script setup>
import { ref }from'vue'
import{ useTable }from'../hooks/useTable'
const url ='https://api.example.com/data'
const{ data, loading, currentPage, total, fetchData }=useTable(url)
constprevPage=()=>{
if(currentPage.value>1){
    currentPage.value--
fetchData()
}
}
constnextPage=()=>{
if(currentPage.value< total.value){
    currentPage.value++
fetchData()
}
}
</script>
<style scoped>
.table-component {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  text-align: center;
  margin-top: 60px;
}
</style>

封装 Hook 时,返回值的设计非常重要。

我们应该返回足够的信息和方法,使得使用 Hook 的组件能够完全控制和使用 Hook 的功能。

在上面的例子中,我们返回了数据、加载状态、当前页码、总页数和一个获取数据的方法。

添加分页查询

有时候,我们需要在表格中支持分页查询。

我们可以在 Hook 中加入分页查询的逻辑,并通过传参控制分页查询的行为。

如何封装

我们在 useTable.js 文件中修改 useTable 函数,加入分页查询的支持:

// src/hooks/useTable.js
import{ ref }from'vue'
import axios from'axios'
exportfunctionuseTable(url, initialParams = {}){
const data =ref([])
const loading =ref(false)
const currentPage =ref(1)
const total =ref(0)
const params =ref(initialParams)
constfetchData=async()=>{
    loading.value=true
try{
const response =await axios.get(url,{
params:{
page: currentPage.value,
...params.value,
},
})
      data.value= response.data.items
      total.value= response.data.total
}catch(error){
console.error('Error fetching data:', error)
}finally{
      loading.value=false
}
}
fetchData()
return{ data, loading, currentPage, total, params, fetchData }
}

在组件中,我们可以传递初始参数,并在查询时修改参数:

<!-- src/components/TableComponent.vue -->
<template>
<div class="table-component">
<input v-model="query" placeholder="Search..." />
<button @click="search">Search</button>
<table v-if="!loading">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr v-for="item in data" :key="item.id">
<td>{{ item.id }}</td>
<td>{{ item.name }}</td>
</tr>
</tbody>
</table>
<p v-else>Loading...</p>
<button @click="prevPage" :disabled="currentPage === 1">Previous</button>
<button @click="nextPage" :disabled="currentPage === total">Next</button>
</div>
</template>
<script setup>
import { ref }from'vue'
import{ useTable }from'../hooks/useTable'
const url ='https://api.example.com/data'
const{ data, loading, currentPage, total, params, fetchData }=useTable(url)
const query =ref('')
constsearch=()=>{
  params.value.query= query.value
fetchData()
}
constprevPage=()=>{
if(currentPage.value>1){
    currentPage.value--
fetchData()
}
}
constnextPage=()=>{
if(currentPage.value< total.value){
    currentPage.value++
fetchData()
}
}
</script>
<style scoped>
.table-component {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  text-align: center;
  margin-top: 60px;
}
</style>

支持不同接口字段

有时候,不同的 API 返回的数据格式可能不同。

我们需要在 Hook 中处理这些不同的字段,以便能够兼容不同的接口。

如何封装

我们在 useTable.js 文件中修改 useTable 函数,加入字段映射的支持:

// src/hooks/useTable.js
import{ ref }from'vue'
import axios from'axios'
exportfunctionuseTable(url, fieldMap = {}, initialParams = {}){
const data =ref([])
const loading =ref(false)
const currentPage =ref(1)
const total =ref(0)
const params =ref(initialParams)
constfetchData=async()=>{
    loading.value=true
try{
const response =await axios.get(url,{
params:{
page: currentPage.value,
...params.value,
},
})
      data.value= response.data[fieldMap.items||'items']
      total.value= response.data[fieldMap.total||'total']
}catch(error){
console.error('Error fetching data:', error)
}finally{
      loading.value=false
}
}
fetchData()
return{ data, loading, currentPage, total, params, fetchData }
}

在组件中,我们可以传递字段映射:

<!-- src/components/TableComponent.vue -->
<template>
<div class="table-component">
<input v-model="query" placeholder="Search..." />
<button @click
="search">Search</button>
<table v-if="!loading">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr v-for="item in data" :key="item.id">
<td>{{ item.id }}</td>
<td>{{ item.name }}</td>
</tr>
</tbody>
</table>
<p v-else>Loading...</p>
<button @click="prevPage" :disabled="currentPage === 1">Previous</button>
<button @click="nextPage" :disabled="currentPage === total">Next</button>
</div>
</template>
<script setup>
import { ref }from'vue'
import{ useTable }from'../hooks/useTable'
const url ='https://api.example.com/data'
const fieldMap ={
items:'results',
total:'total_count',
}
const{ data, loading, currentPage, total, params, fetchData }=useTable(url, fieldMap)
const query =ref('')
constsearch=()=>{
  params.value.query= query.value
fetchData()
}
constprevPage=()=>{
if(currentPage.value>1){
    currentPage.value--
fetchData()
}
}
constnextPage=()=>{
if(currentPage.value< total.value){
    currentPage.value++
fetchData()
}
}
</script>
<style scoped>
.table-component {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  text-align: center;
  margin-top: 60px;
}
</style>

总结

以上便是我对如何在 Vue 3 项目中封装一个超级好用的 Hook 的一些心得与体会。

目录
打赏
0
1
1
0
59
分享
相关文章
高效工作流:用Mermaid绘制你的专属流程图;如何在Vue3中导入mermaid绘制流程图
mermaid是一款非常优秀的基于 JavaScript 的图表绘制工具,可渲染 Markdown 启发的文本定义以动态创建和修改图表。非常适合新手学习或者做一些弱交互且自定义要求不高的图表 除了流程图以外,mermaid还支持序列图、类图、状态图、实体关系图等图表可供探索。 博客不应该只有代码和解决方案,重点应该在于给出解决方案的同时分享思维模式,只有思维才能可持续地解决问题,只有思维才是真正值得学习和分享的核心要素。如果这篇博客能给您带来一点帮助,麻烦您点个赞支持一下,还可以收藏起来以备不时之需,有疑问和错误欢迎在评论区指出~
你真的会使用Vue3的onMounted钩子函数吗?Vue3中onMounted的用法详解
onMounted作为vue3中最常用的钩子函数之一,能够灵活、随心应手的使用是每个Vue开发者的必修课,同时根据其不同写法的特性,来选择最合适最有利于维护的写法。博客不应该只有代码和解决方案,重点应该在于给出解决方案的同时分享思维模式,只有思维才能可持续地解决问题,只有思维才是真正值得学习和分享的核心要素。如果这篇博客能给您带来一点帮助,麻烦您点个赞支持一下,还可以收藏起来以备不时之需,有疑问和错误欢迎在评论区指出~
Pinia 如何在 Vue 3 项目中进行安装和配置?
Pinia 如何在 Vue 3 项目中进行安装和配置?
管理数据必备;侦听器watch用法详解,vue2与vue3中watch的变化与差异
一篇文章同时搞定Vue2和Vue3的侦听器,是不是很棒?不要忘了Vue3中多了一个可选项watchEffect噢。 博客不应该只有代码和解决方案,重点应该在于给出解决方案的同时分享思维模式,只有思维才能可持续地解决问题,只有思维才是真正值得学习和分享的核心要素。如果这篇博客能给您带来一点帮助,麻烦您点个赞支持一下,还可以收藏起来以备不时之需,有疑问和错误欢迎在评论区指出~
除了provide/inject,Vue3中还有哪些方式可以避免v-model的循环引用?
需要注意的是,在实际开发中,应根据具体的项目需求和组件结构来选择合适的方式来避免`v-model`的循环引用。同时,要综合考虑代码的可读性、可维护性和性能等因素,以确保系统的稳定和高效运行。
136 56
创建vue3项目步骤以及安装第三方插件步骤【保姆级教程】
这是一篇关于创建Vue项目的详细指南,涵盖从环境搭建到项目部署的全过程。
291 1
vue3使用pinia中的actions,需要调用接口的话
通过上述步骤,您可以在Vue 3中使用Pinia和actions来管理状态并调用API接口。Pinia的简洁设计使得状态管理和异步操作更加直观和易于维护。无论是安装配置、创建Store还是在组件中使用Store,都能轻松实现高效的状态管理和数据处理。
177 3
|
3月前
|
vue使用iconfont图标
vue使用iconfont图标
168 1
极致的灵活度满足工程美学:用Vue Flow绘制一个完美流程图
本文介绍了使用 Vue Flow 绘制流程图的方法与技巧。Vue Flow 是一个灵活强大的工具,适合自定义复杂的流程图。文章从环境要求(Node.js v20+ 和 Vue 3.3+)、基础入门案例、自定义功能(节点与连线的定制、事件处理)到实际案例全面解析其用法。重点强调了 Vue Flow 的高度灵活性,虽然预定义内容较少,但提供了丰富的 API 支持深度定制。同时,文中还分享了关于句柄(handles)的使用方法,以及如何解决官网复杂案例无法运行的问题。最后通过对比 mermaid,总结 Vue Flow 更适合需要高度自定义和复杂需求的场景,并附带多个相关技术博客链接供进一步学习。

热门文章

最新文章

AI助理

你好,我是AI助理

可以解答问题、推荐解决方案等