引入element-ui
npm 的方式安装 element-ui
npm i element-ui -S
在 main.js 中写入以下内容:
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
Vue.use(ElementUI)
新建Table.vue
主要就是tableListener()方法,监听dom的scroll事件
dom.scrollHeight - dom.scrollTop - dom.clientHeight = 0代表滚动到表格底部
<template> <div id="app"> <el-table :data="tableData" style="width: 100%" height="250" ref="myTable"> <el-table-column type="index" width="50"> </el-table-column> <el-table-column prop="email" label="邮箱"> </el-table-column> <el-table-column prop="name" label="姓名"> </el-table-column> <el-table-column prop="address" label="地址"> </el-table-column> </el-table> </div> </template> <script> import jsonData from './../data/data.json' export default { name: 'Table', components: {}, data() { return { tableData: [], currentPage: 1, pageSize: 10, totalPage: 0 } }, created() { this.totalPage = jsonData.length / this.pageSize this.loadData() }, mounted() { this.tableListener() }, methods: { loadData() { console.log('getData') //这里模拟请求数据,最后一页数据不够pageSize时有BUG,暂不处理 let data = jsonData.splice((this.currentPage - 1) * this.pageSize, this.pageSize) this.tableData = this.tableData.concat(data); console.log("表格数据量:",this.tableData.length) }, tableListener() { console.log("监听表格dom对象的滚动事件") let that = this; let dom = that.$refs.myTable.bodyWrapper dom.addEventListener("scroll", function () { const scrollDistance = dom.scrollHeight - dom.scrollTop - dom.clientHeight; // console.log("scroll", scrollDistance) if (scrollDistance <= 0) {//等于0证明已经到底,可以请求接口 if (that.currentPage < that.totalPage) {//当前页数小于总页数就请求 that.currentPage++;//当前页数自增 //请求接口的代码 that.loadData() } } }) } }, } </script>
data.json数据用 json-generator在线生成 [ '{{repeat(5, 2000)}}', { _id: '{{objectId()}}', name: '{{firstName()}} {{surname()}}', email: '{{email()}}', address: '{{integer(100, 999)}} {{street()}}, {{city()}}, {{state()}}, {{integer(100, 10000)}}' } ]
App.vue中引用子组件table显示
<template> <div id="app"> <Table></Table> </div> </template> <script> import Table from './components/Table.vue' export default { name: 'App', components: { Table }, } </script>
效果
滚动到底部加载下一页数据
-------------------------------------------------------------
智一面|前端模拟面试练习提升题