效果图:
<template>
<div>
<ul style="text-align: left;color: red;">
<li v-for="val in select" :key="val.id">
{{ val.id }}
</li>
</ul>
<div class="page">
<div class="gu">
<span>共多少{{ tatol }}条</span>
<select v-model="pages">
<option value="2" @click="seletPage">2条/页</option>
<option value="4" @click="seletPage">4条/页</option>
</select>
<button @click="upPage">上一页</button>
</div>
<ul class="left" >
<!-- 这里是点击当前元素高亮 其他元素样式清空!!! -->
<li v-for="(val,index) in pageList" :key="index" @click="changePage(index)" :class="{add: index === currentPage}">
{{ val }}
</li>
</ul>
<button>下一页</button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
list: [
{ id: "1" },
{ id: "2" },
{ id: "3" },
{ id: "4" },
{ id: "5" },
{ id: "6" },
{ id: "7" },
{ id: "8" },
{ id: "9" },
{ id: "10" },
{ id: "11" },
{ id: "12" },
],
// 共多少条数据
tatol: "",
// 默认每页展示2条数据
pages: 2,
// 当前页面存放的值
select: "",
// 当前是第几页
currentPage: 0,
// 索引页值 123
pageList: [],
};
},
mounted() {
this.tatol = this.list.length;
this.seletPage();
// 初始第一页
this.changePage(0)
// this.run(this.list,2)
},
methods: {
// 总共显示几页
seletPage() {
console.log("触发了方法");
// this.select = this.list.slice(0, this.pages);
this.pageList = Math.ceil(this.tatol / this.pages);
},
upPage() {
if (this.currentPage == 0) {
alert("已经是第一页");
}else {
this.currentPage --
}
},
changePage(index) {
console.log(index);
// 点击当前的页面
this.currentPage = index
this.select = this.splitPage(this.list, this.pages)
this.select = this.select[index]
},
// 分页 arr需要分页的数组, pageSize几条数据一页 ,
splitPage(arr,pageSize) {
const result = [];
let count = 0;
while (count * pageSize < arr.length) {
result.push(arr.slice(count * pageSize, pageSize * (count + 1)))
count++;
}
return result
}
},
watch: {
// 监听pages的数据,来更新视图
pages() {
console.log("触发了监听");
this.select = this.list.slice(0, this.pages);
this.pageList = Math.ceil(this.tatol / this.pages);
// 改变每页多少条时,需要回到第一页
this.changePage(0)
},
},
};
</script>
.page {
display: flex;
width: 500px;
.gu {
width: 200px;
}
.left {
width: 200px;
display: flex;
justify-content: space-around;
align-self: center;
li {
width: 30px;
}
// li:first-child {
// background-color: pink;
// }
}
button {
flex: 1;
}
}
.add {
background-color: paleturquoise;
}