|
| 1 | +<script setup lang="ts"> |
| 2 | +import type { IProducts } from './typing'; |
| 3 | +
|
| 4 | +import { type Ref, ref } from 'vue'; |
| 5 | +
|
| 6 | +import { keepPreviousData, useQuery } from '@tanstack/vue-query'; |
| 7 | +import { Button } from 'ant-design-vue'; |
| 8 | +
|
| 9 | +const LIMIT = 10; |
| 10 | +const fetcher = async (page: Ref<number>): Promise<IProducts> => { |
| 11 | + const res = await fetch( |
| 12 | + `https://dummyjson.com/products?limit=${LIMIT}&skip=${(page.value - 1) * LIMIT}`, |
| 13 | + ); |
| 14 | + return res.json(); |
| 15 | +}; |
| 16 | +
|
| 17 | +const page = ref(1); |
| 18 | +const { data, error, isError, isPending, isPlaceholderData } = useQuery({ |
| 19 | + // The data from the last successful fetch is available while new data is being requested. |
| 20 | + placeholderData: keepPreviousData, |
| 21 | + queryFn: () => fetcher(page), |
| 22 | + queryKey: ['products', page], |
| 23 | +}); |
| 24 | +const prevPage = () => { |
| 25 | + page.value = Math.max(page.value - 1, 1); |
| 26 | +}; |
| 27 | +const nextPage = () => { |
| 28 | + if (!isPlaceholderData.value) { |
| 29 | + page.value = page.value + 1; |
| 30 | + } |
| 31 | +}; |
| 32 | +</script> |
| 33 | + |
| 34 | +<template> |
| 35 | + <div class="flex gap-4"> |
| 36 | + <Button size="small" @click="prevPage">上一页</Button> |
| 37 | + <p>当前页: {{ page }}</p> |
| 38 | + <Button size="small" @click="nextPage">下一页</Button> |
| 39 | + </div> |
| 40 | + <div class="p-4"> |
| 41 | + <div v-if="isPending">加载中...</div> |
| 42 | + <div v-else-if="isError">出错了: {{ error }}</div> |
| 43 | + <div v-else-if="data"> |
| 44 | + <ul> |
| 45 | + <li v-for="item in data.products" :key="item.id"> |
| 46 | + {{ item.title }} |
| 47 | + </li> |
| 48 | + </ul> |
| 49 | + </div> |
| 50 | + </div> |
| 51 | +</template> |
0 commit comments