vue3中setup使用组合式函数提取分页逻辑(简单示例)

参照官网,如需参照请点击

组件中使用

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)

以上是自己理解,欢迎指正
官方解释连接

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值