大家好,我是CodeQi!
在 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=tr