【前端】vue+html+js 实现table表格展示,以及分页按钮添加

一. 问题描述

数据条数太多显示到页面上时可能会渲染较慢,因此需要截取数据进行展示。

二. 代码写法

思路:按照上述图示思路,需要有两个数据列表,一个存储的是所有的列表数据,一个存储的是展示的数据列表,程序开始后先选择数据头部的几条数据。因此也会需要一个当前第几页的参数。

2.1 代码展示

html部分

v-for展示列表,以及两个按钮对当前页面进行选择。

html 复制代码
  <div id="app">
    <!-- 数据列表 -->
    <ul>
      <li v-for="item in currentPageData" :key="item.id">{{ item.name }}</li>
    </ul>
    <!-- 分页器 -->
    <div>
      <button @click="prevPage">上一页</button>
      <span>{{ currentPage }}</span>
      <button @click="nextPage">下一页</button>
    </div>
  </div>

Js部分

利用created生命周期钩子进行数据初始化。计算属性进行展示列表更新。

javascript 复制代码
<script>
    // 创建Vue实例
    new Vue({
      el: '#app',
      data: {
        currentPage: 1, // 当前页码
        pageSize: 4, // 每页显示的数据条数
        dataList: [], // 数据列表
        totalPages:0,
      },      
      created() {
 
        // ajax请求获取数据
        // 这里使用setTimeout模拟异步请求
          this.dataList = [
            { id: 1, name: '数据1' },
            { id: 2, name: '数据2' },
            { id: 3, name: '数据1' },
            { id: 4, name: '数据2' },
            { id: 5, name: '数据1' },
            { id: 6, name: '数据2' },
            { id: 7, name: '数据1' },
            { id: 8, name: '数据2' },
            { id: 9, name: '数据1' },
            { id: 10, name: '数据2' },
            { id: 11, name: '数据1' },
            { id: 12, name: '数据2' },
            { id: 13, name: '数据1' },
            { id: 14, name: '数据2' },
            { id: 100, name: '数据100' },
          ];
        this.totalPages = Math.ceil(this.dataList.length/this.pageSize);          
    },
      computed: {
        // 计算属性,根据当前页码和每页显示的数据条数,计算当前页显示的数据
        currentPageData() {
          const start = (this.currentPage - 1) * this.pageSize;
          const end = start + this.pageSize;
          return this.dataList.slice(start, end);
        },
      },
      methods: {
        // 上一页
        prevPage() {
          if (this.currentPage > 1) {
            this.currentPage--;
          }
        },
        // 下一页
        nextPage() {
          if (this.currentPage < this.totalPages) {
            this.currentPage++;
          }
        },
      },
    });
  </script>
相关推荐
酒尘&3 小时前
JS数组不止Array!索引集合类全面解析
开发语言·前端·javascript·学习·js
学历真的很重要3 小时前
VsCode+Roo Code+Gemini 2.5 Pro+Gemini Balance AI辅助编程环境搭建(理论上通过多个Api Key负载均衡达到无限免费Gemini 2.5 Pro)
前端·人工智能·vscode·后端·语言模型·负载均衡·ai编程
用户47949283569154 小时前
"讲讲原型链" —— 面试官最爱问的 JavaScript 基础
前端·javascript·面试
用户47949283569154 小时前
2025 年 TC39 都在忙什么?Import Bytes、Iterator Chunking 来了
前端·javascript·面试
JIngJaneIL4 小时前
基于Java非遗传承文化管理系统(源码+数据库+文档)
java·开发语言·数据库·vue.js·spring boot
+VX:Fegn08954 小时前
计算机毕业设计|基于springboot + vue心理健康管理系统(源码+数据库+文档)
数据库·vue.js·spring boot·后端·课程设计
大怪v5 小时前
【Virtual World 04】我们的目标,无限宇宙!!
前端·javascript·代码规范
狂炫冰美式6 小时前
不谈技术,搞点文化 🧀 —— 从复活一句明代残诗破局产品迭代
前端·人工智能·后端
xw56 小时前
npm几个实用命令
前端·npm
!win !6 小时前
npm几个实用命令
前端·npm