【前端】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>
相关推荐
霍理迪15 分钟前
Vue的响应式和生命周期
前端·javascript·vue.js
李剑一19 分钟前
别再瞎写了!Cesium 模型 360° 环绕,4 套源码全公开,项目直接用
前端
小码哥_常37 分钟前
Android消息机制:Handler、Looper和Message的深度剖析
前端
小码哥_常40 分钟前
安卓开发新姿势:文件Picker全攻略,无痛适配不再难
前端
happymaker06261 小时前
web前端学习日记——DAY04
前端·学习
发现一只大呆瓜1 小时前
React-路由监听 / 跳转 / 守卫全攻略(附实战代码)
前端·react.js·面试
swipe2 小时前
为什么 RAG 一定离不开向量检索:从文档向量化到语义搜索的工程实现
前端·llm·agent
OpenTiny社区2 小时前
AI-Extension:让 AI 真的「看得到、动得了」你的浏览器
前端·ai编程·mcp
IT_陈寒2 小时前
Redis缓存击穿:3个鲜为人知的防御策略,90%开发者都忽略了!
前端·人工智能·后端
竹林8183 小时前
在Web3前端用Node.js子进程批量校验钱包,我踩了这些性能与安全的坑
javascript·node.js