组件效果如下:

技术亮点:
1.封装分页组件,不需要在外部页面维护公共数据,只需要在公共数据部分维护该分页器实例本身即可
2.所有的数据都在内部实现计算,存储, 多个分页器实例都是新的单例(工厂模式),都是独立的存在,不用担心分页器之间的数据粘连
开发思路:
主要用了setter getter以及事件侦听抛发机制,及时的实现数据视图的双向通信
外部使用示例:


注意点:
1.属性写在方法外面是ES7的写法,而webpack打包时,必须要装babel的plugin才能打包,否则出错。所以这里临时的解决方案是在构造函数内及init函数内创建类中需要调用的属性
2.如果有其他需求,则外部可以操作改变pageSize,total,currentPage三个属性的改变
组件代码如下:
export default class paginations extends EventTarget{
constructor(_eventType) {//初始化时需要声明自定义事件类型,指定数据抛发的指向对象
super();
this.elem = this.createElem();//放分页器的容器
this.elem.className="paganitionCon"
this.elem.addEventListener("click", (e) => this.clickHandler(e));
this.eventType = _eventType;
this.init();//初始化样式,没有数据
this.render();
this.hightlight();
}
init() {
this._pageSize = 3;//每页显示条目个数
this._total = 0;//总条目数
this._currentPage = 1;//当前页数
this.pageCount = Math.ceil(this.total / this.pageSize);//需要渲染的页数
}
createElem(){
if(this.elem) return this.elem;
let div=document.createElement("div");
return div;
}
appendTo(parent){
if(typeof parent==="string")parent=document.querySelector(parent);
parent.appendChild(this.elem);
}
set total(value) {//当总条数改变时,total改变
this._total = value;
this.pageCount = Math.ceil(this.total / this.pageSize);
this.render();
this.hightlight();
}
get total() {
return this._total;
}
set pageSize(value) {//每页显示条目个数改变时,触发改变
this._pageSize = value;
this.pageCount = Math.ceil(this.total / this.pageSize);
this.render();
this.hightlight();
}
get pageSize() {
return this._pageSize;
}
set currentPage(value) {
this._currentPage = value;
this.render();
this.hightlight();
}
get currentPage() {
return this._currentPage;
}
render() {
this.elem.innerHTML = "";
this.elem.innerHTML = `
<ul class="pagination pagination-sm no-margin pull-right" id="paginationModule">
<li><a href="javascript:;" class="left">«</a></li>
${(function (pageCount) {
var arr = [];
for (let i = 1; i <= pageCount; i++){
arr.push("<li><a href='javascript:void(0)'>" + i + "</a></li>");
}
return arr.join("");
})(this.pageCount)}
<li><a href="javascript:;" class="right">»</a></li>
</ul>`;
}
clickHandler(e) {
if (e.target.nodeName !== "A") return;
switch (e.target.className) {
case "":
this.currentPage = Number(e.target.textContent);
break;
case "left":
if (this.currentPage > 1) this.currentPage--;
else this.currentPage = 1;
break;
case "right":
if (this.currentPage < this.pageCount) this.currentPage++;
else this.currentPage = this.pageCount;
break;
}
this.dispatch(this.currentPage);
}
hightlight() {
this.liArr = this.elem.querySelectorAll("li");//存储所有的页数对应的li
if (this.prev) this.prev.className = "";//给prev设置为active,prev是指需要高亮的页数
if (this.currentPage) {//当数据全部删除完,则无高亮效果
this.prev = this.liArr[this.currentPage];
this.prev.className = "active";
}
}
dispatch(currentPage) {
let evt = new Event(this.eventType);
evt.data = {
currentPage
}
this.dispatchEvent(evt);
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。