vue使用数据来驱动效果展示,使用vue来制作分页是一种什么样的体验呢,接下来我就来实现一个简单的分页
首先我们要查看一下分页规则,我们会发现这样的规律:
1 2 3 4 5 | /* 1-10 let i=1;i<=10;i++ 11-20 let i=10*1+1;i<=10*2;i++ 21-30 let i=10*2+1;i<=10*3;i++ */ |
从上我们可以知道10是不变的,10代表的就是一个页面的个数,我们就可以编写循环来循环当前的数据,如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 | <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>vue实现极简页面分页-国瑞前端</title> <script src="https://cdn.bootcss.com/vue/2.5.18-beta.0/vue.min.js"></script> <style> * { margin: 0; padding: 0; } </style> </head> <body> <div id="app"> <template v-for="(item,index) in curList"> <p> {{item.message}}</p> </template> 数据共有{{list.length-1}}条分页: <button v-for="item in page " @click="pages(item)" :disable='true' :disabled="item===curPage">当前为第{{item}}页</button> </div> </body> </html> <script> new Vue({ el: "#app", data: { list: [], curList: [], page: 1, //默认的第一页 curPage: 1, //当前页数 pageSize: 45, //数据条数 size: 10, //一页有多少数据 redundant: 0 //最后一页数据处理 }, methods: { apiList() { //模拟假数据 this.list.push('aaa') for (let i = 1; i <= this.pageSize; i++) this.list.push({ message: `当前数据为${i}` }) this.redundant = this.pageSize % this.size console.log(' this.redundant===', this.redundant) this.page = Math.ceil(this.pageSize / this.size) console.log(this.size) }, pages(index) { this.curPage = index this.curList = [] console.log(`当前的页码为${index}-------------------------${index*this.size}`) for (let i = (this.size * (index - 1) + 1); i <= (index * this.size); i++) if (index === 1) { this.curList.push(this.list[i]) } else this.curList.push(this.list[i]) if (index === this.page) { this.curList = [] for (let i = (this.size * (index - 1) + 1); i <= (index * this.size - this.redundant); i++) this.curList.push(this.list[i]) } } }, created() { this.apiList() this.pages(1) } }) /* 1-10 let i=1;i<=10;i++ 11-20 let i=10*1+1;i<=10*2;i++ 21-30 let i=10*2+1;i<=10*3;i++ */ </script> |
7