用js实现的分页结果如图所示:
css
.page-bar{ margin:40px; } ul,li{ 0px; padding: 0px; } li{ list-style: none } .page-bar li:first-child>a { margin-left: 0px } .page-bar a{ border: 1px solid #ddd; text-decoration: none; position: relative; float: left; 6px 12px; margin-left: -1px; line-height: 1.42857143; color: #337ab7; cursor: pointer } .page-bar a:hover{ background-color: #eee; } .page-bar a.banclick{not-allowed; } .page-bar .active a{ #fff; default; border-color: #337ab7; } .page-bar i{ font-style:normal; #d44950; 0px 4px; font-size: 12px; }
模版
<div class="page-bar"> ul> li v-if="cur>1"><a v-on:click="cur--,pageClick()">上一页</a></li="cur==1"="banclick"v-for="index in indexs" v-bind:class="{ 'active': cur == index}"> ="btnClick(index)">{{ index }}="cur!=all"="cur++,1)">>下一页="cur == all">共i>{{all}}>页> div>
js
var pageBar = new Vue({ el: '.page-bar',data: { all: 20,//总页数 cur: 1,1)">当前页码 });
调用 new Vue({参数})
就是创建了一个基本的组件,赋值给变量 pageBar.
el就是element的缩写,定位模版的位置.data就是数据了.
知道了总页数但是要显示页码还是要一番计算,所以显示页码就是计算属性了.
所以我们要用computed
computed: { indexs: function(){ var left = 1; var right = this.all; var ar = []; if(this.all>= 5){ this.cur > 3 && this.cur < this.all-2){ left = this.cur - 2 right = this.cur + 2 }else{ this.cur<=3){ left = 1 right = 5 }{ right = .all left = this.all -4 } } } while (left <= right){ ar.push(left) left ++ } return ar } }
>
v-for
是循环渲染输出计算属性indexs.每一次循环的子元素赋值给index v-bind:class
绑定class,当渲染到目前的角标的时候加个class v-on:click
是绑定了事件,我把index当参数传进入了,后面做判断,默认传event事件.
然后我们给Vue的选项里面再增加methods字段
methods: { btnClick: function(data){页码点击事件 if(data != .cur){ this.cur = data } },pageClick: (){ console.log('现在在'+this.cur+'页'); } },
组件交互
组件写完了,问题来了,用户点击发生页面改变,你怎么通知其他组件作出相应的变化. 可以在页角发生改变的函数下,插一条语句通知其他组件。不过这种方法是很差的做法。可以使用
watch: { cur: (oldValue,newValue){ console.log(arguments); } }
观察了cur数据当它改变的时候,可以获取前后值。然后通知其他组件。
完整的代码:
<!DOCTYPE htmlhtmlheadMeta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no"/> charset="utf-8"title="keywords"="" ="description"script type="text/javascript" src="js/vue.min.js"scriptstyle> .page-bar{ margin:40px; } 0px; padding li list-style none .page-bar li:first-child>a margin-left 0px .page-bar a border 1px solid #ddd text-decoration none position relative float left 6px 12px margin-left -1px line-height 1.42857143 color #337ab7 cursor pointer .page-bar a:hover background-color #eee .page-bar a.banclicknot-allowed .page-bar .active a #fff default border-color .page-bar i font-stylenormal #d44950 0px 4px font-size 12px} body> ="text/javascript"> var pageBar = new Vue({ el: '.page-bar8//总页数 cur: 1当前页码 },watch: { cur: function(data){页码点击事件 if(data != this.cur){ .cur =(){ console.log(现在在+.cur页(){ left ; right .all; ar []; (.all>= 5){ > 3 && < -2){ left - right + }else{ <=3 }{ right .all left .all 4 } } } while (left right){ ar.push(left) left ++ } return ar } } }) >
参考地址
https://www.zhihu.com/question/37174943
https://segmentfault.com/a/1190000003931500