如何在html里封装vue组件,基于Vue如何封装分页组件

使用Vue做双向绑定的时候,可能经常会用到分页功能

接下来我们来封装一个分页组件

先定义样式文件 pagination.css

ul, li {

margin: 0px;

padding: 0px;

}

.page-bar {

-webkit-touch-callout: none;

-webkit-user-select: none;

-khtml-user-select: none;

-moz-user-select: none;

-ms-user-select: none;

user-select: none;

}

.page-button-disabled {

color:#ddd !important;

}

.page-bar li {

list-style: none;

display: inline-block;

}

.page-bar li:first-child > a {

margin-left: 0px;

}

.page-bar a {

border: 1px solid #ddd;

text-decoration: none;

position: relative;

float: left;

padding: 6px 12px;

margin-left: -1px;

line-height: 1.42857143;

color: #337ab7;

cursor: pointer;

}

.page-bar a:hover {

background-color: #eee;

}

.page-bar .active a {

color: #fff;

cursor: default;

background-color: #337ab7;

border-color: #337ab7;

}

.page-bar i {

font-style: normal;

color: #d44950;

margin: 0px 4px;

font-size: 12px;

}

js文件 pagination.js

(function (vue) {

// html模板信息

var template = '

\ \
'

var pagination = vue.extend({

template: template,

props: ['cur', 'all'],

computed: {

indexs: function () {

var left = 1

var right = this.all

var ar = []

if (this.all >= 11) {

if (this.cur > 5 && this.cur < this.all - 4) {

left = this.cur - 5

right = this.cur + 4

} else {

if (this.cur <= 5) {

left = 1

right = 10

} else {

right = this.all

left = this.all - 9

}

}

}

while (left <= right) {

ar.push(left)

left++

}

if (ar[0] > 1) {

ar[0] = 1;

ar[1] = -1;

}

if (ar[ar.length - 1] < this.all) {

ar[ar.length - 1] = this.all;

ar[ar.length - 2] = 0;

}

return ar

}

},

methods: {

// 页码点击事件

btnClick: function (data) {

if (data < 1) return;

if (data != this.cur) {

this.cur = data

this.$dispatch('btn-click', data)

}

},

// 下一页

nextPage: function (data) {

if (this.cur >= this.all) return;

this.btnClick(this.cur + 1);

},

// 上一页

prvePage: function (data) {

if (this.cur <= 1) return;

this.btnClick(this.cur - 1);

},

// 设置按钮禁用样式

setButtonClass: function (isNextButton) {

if (isNextButton) {

return this.cur >= this.all ? "page-button-disabled" : ""

}

else {

return this.cur <= 1 ? "page-button-disabled" : ""

}

}

}

})

vue.Pagination = pagination

})(Vue)

pagination分页组件就封装好了,需要使用的时候,引入以上两个文件即可

接下来我们测试下效果

{{msg}}

var app = new Vue({

el: '#app',

data: {

// 当前页码

cur: 1,

// 总页数

all: 100,

msg: ''

},

components: {

// 引用组件

'vue-pagination': Vue.Pagination

},

methods: {

listen: function (data) {

// 翻页会触发此事件

this.msg = '当前页码:' + data

}

}

})

最终效果

c88b00904189e1340bb683254968eb3a.png

页码切换事件在listen中处理即可

点击此处下载源码:源码下载地址

以上所述是小编给大家介绍的基于Vue如何封装分页组件,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值