栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > Web开发 > Vue.js

使用Vue开发一个分页插件

Vue.js 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用Vue开发一个分页插件

组件是Vue最强大的功能之一,可以扩展HTML功能,封装可重用的代码。分页组件是网页中常用的,本篇文章介绍如何简单封装一个分页组件。

我们使用全局注册的方式来开发一个组件,形式如下:

Vue.component('组件名称',{
 ...配置项
});
思路

我们通过props传入参数,在page组件内部计算需要显示的页码。

//props 参数
total//数据总条数
pagesize    //每页显示数
page //当前页码

总页数计算:Math.ceil(total/pagesize)

当页码改变时,触发一个pagechange事件,父组件中可以捕获该事件。
代码
 Vue.component('page',{
 props:{
      total:{
 type:[Number,String],
 default:0
      },
      pagesize:{
 type:[Number,String],
 default:1
      },
      page:{
 type:[Number,String],
 default:1
      }
 },
 template:''+
'
    '+ '
  • 上一页
  • '+ '
  • 首页
  • '+ '
  • '+ '{{item}}'+ '
  • '+ '
  • 尾页
  • '+ '
  • 下一页
  • '+ '
  • 总共{{totalCount}}页
  • '+ '
'+ '', data(){ return { totalCount:0 //总页数 } }, computed:{ list(){ let list=[]; //计算总页数 this.totalCount=Math.ceil(this.total/this.pagesize); //超限控制 if(this.page<=0){ this.page=1; } if(this.page>this.totalCount){ this.page=this.totalCount; } //计算显示页码 if(this.totalCount>5){ if(this.page>2&&this.page0){ for(let i=1;i<=5;i++){ list.push(i); } }else if(this.page>=this.totalCount-2&&this.page<=this.totalCount){ for(let i=4;i>=0;i--){ list.push(this.totalCount-i); } } }else{ for(let i = 1;i<=this.totalCount;i++){ list.push(i); } } return list; } }, methods:{ //页码点击事件 handleClick(e){ let page=parseInt(e.target.innerText); let {count,total }=this; this.$emit('pagechange',{page,count,total}); }, //前一页 prev(e){ if(!e.target.classList.contains['disable']){ this.page>1&&this.page--; let {page,count,total }=this; this.$emit('pagechange',{page,count,total}); } }, //下一页 next(e){ if(!e.target.classList.contains['disable']){ this.page 样式
     div.page{
   font-size: 12px;
   font-family:'Franklin Gothic Medium', 'Arial Narrow', Arial, sans-serif;
   color: #666;
   user-select: none;
}
div.page ul{
  padding: 0;
  margin:0;
}
div.page ul li{
  display: inline-block;
  min-width:30px;
  min-height:30px;
  border-radius:3px;
  line-height: 30px;
  text-align: center;
  margin: 0 6px;
  cursor: pointer;
}
div.page ul li.active{
  background: #1796e0;
  color:#fff;
}
div.page ul li.disable{
  color: #ccc;
}

使用方式
//html代码
...

     


//js代码
 new Vue({
 el:'#app',
 data:{
     page:1,
     pageSize:5,
     total:100
 },
 methods:{
   pageChange(e){
     this.page=e.page;
   }
 }
 });
...

最终效果:

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/240292.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号