Vue 3 的组合式 API 可以使用'ref'和'computed'来实现分页查询。

首先,我们需要定义一个'ref'来存储当前页码和每页显示的数量:

import { ref } from 'vue'

export default function usePagination() {
  const currentPage = ref(1)
  const pageSize = ref(10)

  return {
    currentPage,
    pageSize
  }
}

然后,我们可以通过计算属性来获取分页查询的结果:

import { computed } from 'vue'

export default function usePagination() {
  // ...

  const data = ref([...]) // 假设这里是要分页查询的数据

  const paginatedData = computed(() => {
    const start = (currentPage.value - 1) * pageSize.value
    const end = start + pageSize.value

    return data.value.slice(start, end)
  })

  return {
    currentPage,
    pageSize,
    paginatedData
  }
}

最后,在组件中使用这个'usePagination'函数:

import { onMounted } from 'vue'
import usePagination from './usePagination'

export default {
  setup() {
    const { currentPage, pageSize, paginatedData } = usePagination()

    onMounted(() => {
      // 这里可以发起分页查询的请求,并更新data的值
    })

    return {
      currentPage,
      pageSize,
      paginatedData
    }
  }
}

现在,我们就可以在模板中使用'currentPage'、'pageSize'和'paginatedData'来展示分页查询的结果了:

<template>
  <div>
    <ul>
      <li v-for="item in paginatedData" :key="item.id">{{ item.name }}</li>
    </ul>
    <button @click="currentPage--" :disabled="currentPage === 1">上一页</button>
    <button @click="currentPage++" :disabled="currentPage === totalPages">下一页</button>
  </div>
</template>

这样,我们就实现了一个简单的分页查询功能。

Vue3 组合式 API 实现分页查询 - 详细教程

原文地址: https://www.cveoy.top/t/topic/qBc9 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录