vue组件通信-综合案例-分页组件
Markup
<style>
*{
margin: 0;
padding: 0;
}
.pagination{
margin: 20px 0;
}
.pagination a{
padding: 5px 12px;
border: 1px solid #3ba9ff;
text-decoration: none;
color: #515151;
margin: 5px;
}
/* 高亮显示 */
.pagination a.active{
background: #3ba9ff;
color: white;
}
</style>
</head>
<body>
<div id="app">
<ul>
<span v-if="showList.length>0">
<li v-for="(item,index) in showList">{{item.name}}</li>
</span>
</ul>
<w-pagination :total="list.length" :pre-page="prePage" :page.sync="uPage">
<template v-slot:footer="props">
一共有{{props.pages}}页,当前第{{props.page}}页
</template>
</w-pagination>
</div>
<template id="webpage">
<div class="pagination">
<a href="" @click.prevent="prev">上一页</a>
<!-- 在子实例的 视图层 通过 v-for 列表渲染 去遍历 ,总共有几个页码
注意:p--表示 当前页码
-->
<a href="" v-for="p in pages"
:class="{active:p==page}"
@click.prevent="gotoPage(p)"
>{{p}}</a>
<a href="" @click.prevent="next">下一页</a>
<slot name="footer" :pages="pages" :page="page"></slot>
</div>
</template>
<script src="js/vue.js"></script>
<script>
// 子实例(子组件---分页组件:通过分页的形式,显示数组中的各项数据---当前这一页,显示数组的哪几条数据,那一页,显示数组的哪几条数据)
let wPagination = {
props:['total','page','prePage'],
template:'#webpage',
data:function(){
return {
pages: Math.ceil(this.total/this.prePage)
}
},
methods:{
gotoPage:function(p){
this.$emit('update:page',p);
},
prev:function(){
if(this.page>=1){
this.$emit('update:page',this.page-1);
}
},
next:function(){
if(this.page<this.pages){
this.$emit('update:page',this.page+1);
}
}
}
}
// 根实例(根组件)
let vm = new Vue({
el:'#app',
// data数据中心--存储某个独立组件内部的私有数据的
data:function(){
return {
list:[
{id:1,name:'网易'},
{id:2,name:'凤凰网'},
{id:3,name:'腾讯'},
{id:4,name:'优酷'},
{id:5,name:'爱奇艺'},
{id:6,name:'芒果TV'},
{id:7,name:'迅雷'},
{id:8,name:'科技.网易'},
{id:9,name:'娱乐.网易'},
{id:10,name:'家居.网易'}
],
uPage:1,
prePage:3
}
},
// 生命周期
// updated 数据更新后 钩子函数
updated:function(){
console.log(this.uPage);
},
// 计算属性
computed:{
// 取数组中的 “几项”数据,显示在“当前”页面
showList:function(){
// 截取的起始 点(位置)
let start = (this.uPage-1) * this.prePage;
let result = this.list.slice(start, start+this.prePage);
return result;
}
},
methods:{
},
components:{
wPagination
}
})
</script>
分析:
点击 分页组件(子组件) 的按钮 1, 子组件的数据 p 的值,传入到 父组件的视图层 :page.sync="uPage"
父组件视图层uPage的数据变化,随着 父组件的数据中心中的uPage 也发生了变化。
这时,父组件的计算属性中的 showList属性上 截取数组的内容,也发生了变化。
start = (1-1)*3=0 ----slice(0,0+3)
start = (2-1)*3=3 ----slice(3,3+3)
start = (3-1)*3=6 ----slice(6,6+3)
start = (4-1)*3=9 ----slice(9,9+3)
