【前端】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>
相关推荐
倚肆1 小时前
CSS 选择器空格使用区别详解
前端·css
盼哥PyAI实验室1 小时前
学会给网页穿衣服——学习 CSS 语言
前端·css·学习
我的xiaodoujiao1 小时前
使用 Python 语言 从 0 到 1 搭建完整 Web UI自动化测试学习系列 25--数据驱动--参数化处理 Excel 文件 2
前端·python·学习·测试工具·ui·pytest
San30.1 小时前
从代码规范到 AI Agent:现代前端开发的智能化演进
javascript·人工智能·代码规范
岁月宁静2 小时前
从0到1:智能汇 AI 全栈实战,拆解多模态 AI 应用开发全流程
前端·vue.js·node.js
廾匸6402 小时前
语义化标签
前端·javascript·html
汪汪队立大功1232 小时前
selenium中执行javascript,是否等价于在浏览器console位置执行
javascript·selenium·测试工具
烛阴2 小时前
隐式vs显式:解密C#类型转换的底层逻辑
前端·c#
Fantasydg2 小时前
AJAX JSON学习
前端·学习·ajax
瓢儿菜20183 小时前
Web开发:什么是 HTTP 状态码?
前端·网络协议·http