组件中使用
HelloWorld.vue
<script setup lang="ts">
import { nextTick, provide,ref, type Ref } from "vue";
import {useFetch} from '../pageCount/page'
let dataList = ref()
let iPage= ref(0)
const clickAdd = async() => {
iPage.value++
const { data } = await useFetch('/pet/findByStatus',iPage.value)
// 这里一定要用setTimeout才能获得 如果不需要操作本组件中的行为则可直接在模版中使用data不必再在组件中存储
setTimeout(() => {
//(每个分页逻辑有单独的其他处理逻辑 可以在各自的组件内请自行操作)
dataList.value = Object.assign({},data.value)
console.log(data.value)
}, 500);
}
</script>
<template>
<div class="greetings">
<button @click="clickAdd">点击加{{iPage}}</button>
<ul><li v-for="item in dataList" :key="item.id">{{item.name}}</li></ul>
</div>
</template>
<style scoped>
</style>
提取的公共逻辑
pages.ts
import { isRef, ref, unref, watchEffect, type Ref } from 'vue'
import Http from "@/servives/request";
interface petItem {
[key:string]: any
}
const data:Ref<petItem[]> = ref([])
// 组合式函数约定用驼峰命名法命名,并以“use”作为开头。
// useFetch() 现在同时可以接收静态的 URL 字符串和 URL 字符串的 ref
export function useFetch(url:string, currentPage?:number) {
const pageObj=ref({
pageSize: 10,
currentPage
})
const error = ref(null)
async function doFetch() {
try {
// 当前页是1的时候
if(pageObj.value.currentPage === 1) {
// unref() 解包可能为 ref 的值
const res = await Http.get(unref(url))
data.value = res
} else {
///当前页不是1的话直接往数组后面添加
const res = await Http.get(unref(url))
data.value = [...data.value, ...res]
}
} catch (error:any) {
error.value = error
}
}
if (isRef(url)) {
// 若输入的 URL 是一个 ref,那么启动一个响应式的请求
watchEffect(doFetch)
} else {
// 否则只请求一次
// 避免监听器的额外开销
doFetch()
}
return { data, error }
}
本人项目目录
后台返回的data数据
{
"name": "料精作",
"photoUrls": [
"http://dummyimage.com/336x280",
"http://dummyimage.com/88x31",
"http://dummyimage.com/160x600"
],
"id": 7414460787117966,
"category": {
"name": "程水",
"id": 64603066
},
"tags": [
{
"name": "族目它类",
"id": 17006931
}
],
"status": "available"
}
注意事项:
1.组合式函数返回一个响应式的对象,会导致这个对象中的失去与组合式内部响应性的连接,用ref可以维持这一响应性连接
2.如果组合式函数中想使用reactive 建议在组件内部再包裹一层reactive
const useFetch = reactive(await useFetch('/pet/findByStatus',iPage.value))
console.log(useFetch.data)
以上是自己理解,欢迎指正
官方解释连接