在Vue3中,可以使用<template>, <script><style> 标签来实现表格分页功能。以下是一个简单的示例代码:

<template>
  <div>
    <table>
      <thead>
        <tr>
          <th>ID</th>
          <th>Name</th>
          <th>Email</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(user, index) in displayedUsers" :key="user.id">
          <td>{{ user.id }}</td>
          <td>{{ user.name }}</td>
          <td>{{ user.email }}</td>
        </tr>
      </tbody>
    </table>
    <div>
      <button @click="previousPage" :disabled="currentPage === 1">Previous</button>
      <span>{{ currentPage }}</span>
      <button @click="nextPage" :disabled="currentPage === totalPages">Next</button>
    </div>
  </div>
</template>

<script>
import { ref, computed } from 'vue';

export default {
  data() {
    return {
      users: [
        { id: 1, name: 'John', email: 'john@example.com' },
        { id: 2, name: 'Jane', email: 'jane@example.com' },
        // ...
      ],
      pageSize: 5,
      currentPage: 1,
    };
  },
  computed: {
    totalPages() {
      return Math.ceil(this.users.length / this.pageSize);
    },
    displayedUsers() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      return this.users.slice(start, end);
    },
  },
  methods: {
    previousPage() {
      this.currentPage--;
    },
    nextPage() {
      this.currentPage++;
    },
  },
};
</script>

<style>
table {
  width: 100%;
  border-collapse: collapse;
}

th, td {
  padding: 8px;
  border-bottom: 1px solid #ddd;
}

button {
  margin: 4px;
}
</style>

在上述代码中,users数组包含了所有的用户数据。pageSize定义了每页显示的记录数,currentPage表示当前页码。

通过计算属性totalPages计算出总页数。计算属性displayedUsers根据当前页码和每页记录数来计算出当前页应该显示的用户数据。

previousPagenextPage方法分别用于切换到上一页和下一页。

最后,使用v-for指令在表格中循环渲染显示的用户数据,并使用按钮来切换页码。

这样,就实现了一个简单的表格分页功能

vue3 实现表格分页功能

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

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