MST
星途 面试题库

面试题:Vue 中如何优雅地处理后端 API 返回的分页数据

假设后端 API 返回的数据结构为 {total: 100, list: []},total 表示数据总数,list 是当前页的数据列表。在 Vue 项目中,你会如何设计组件来展示分页数据,并处理分页逻辑与后端 API 的交互?请简述思路并给出关键代码片段。
28.4万 热度难度
前端开发Vue

知识考点

AI 面试

面试题答案

一键面试

思路

  1. 数据初始化:在组件的 data 中定义当前页码、每页数据量、总数据量以及数据列表。
  2. 获取数据:在 created 钩子函数中调用获取数据的方法,传递当前页码和每页数据量给后端 API。
  3. 分页逻辑:实现上一页、下一页、跳转到指定页等方法,根据当前页码和每页数据量重新请求数据。
  4. 展示数据:在模板中循环展示 list 中的数据,并展示分页相关的按钮和页码信息。

关键代码片段

<template>
  <div>
    <ul>
      <li v-for="item in list" :key="item.id">{{ item.name }}</li>
    </ul>
    <div>
      <button @click="prevPage" :disabled="currentPage === 1">上一页</button>
      <span>{{ currentPage }}</span>
      <button @click="nextPage" :disabled="currentPage * pageSize >= total">下一页</button>
      <input type="number" v-model="targetPage" />
      <button @click="goToPage">跳转</button>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      currentPage: 1,
      pageSize: 10,
      total: 0,
      list: [],
      targetPage: 1
    };
  },
  created() {
    this.fetchData();
  },
  methods: {
    async fetchData() {
      const response = await this.$http.get('/api/data', {
        params: {
          page: this.currentPage,
          pageSize: this.pageSize
        }
      });
      this.total = response.data.total;
      this.list = response.data.list;
    },
    prevPage() {
      if (this.currentPage > 1) {
        this.currentPage--;
        this.fetchData();
      }
    },
    nextPage() {
      if (this.currentPage * this.pageSize < this.total) {
        this.currentPage++;
        this.fetchData();
      }
    },
    goToPage() {
      const validPage = Math.max(1, Math.min(this.targetPage, Math.ceil(this.total / this.pageSize)));
      if (validPage!== this.currentPage) {
        this.currentPage = validPage;
        this.fetchData();
      }
    }
  }
};
</script>