我以一个分页组件来分析
首先,新建了一个page.vue的文件,作为子组件,按照需要将标签样式等写好,我的路径是src/components/page.vue
子组件中设置props,用来接收父组件传递的值,这里我设置了两个值,一个totalCount用来接收总页数,一个input用来接收当前页码
props:['totalCount','input'],
父组件传递过来的totalCount 的值,在子组件中不需要处理,所以可以在子组件中直接调用
<span style="margin-left:10px;">共 {
{totalCount}} 页</span>
input值需要在子组件中稍作处理,所以需要在子组件中声明一个变量来接收,用watch函数来监听父组件传来的input值,在子组件中操作声明的变量,这么做的原因呢,可以看一下Vue官方文档的prop
对于子组件上绑定的方法,可以用$emit(event,params)来监听,event为父组件中的方法,params为传递的参数
<el-input v-model="page" @blur="handleChangeSize(page)"></el-input>
handleChangeSize(input){
this.$emit('pageSize',input)
},
具体代码如下:
子组件
<template>
<div class="page">
<i class="el-icon-caret-left" title="上一页" @click="prev"></i>
<span>第<el-input v-model="page" @blur="handleChangeSize(page)"></el-input>页</span>
<span style="margin-left:10px;">共 {
{totalCount}} 页</span>
<i class="el-icon-caret-right" title="下一页" @click="next"></i>
</div>
</template>
<script>
export default{
name:'page',
props:['totalCount','input'],
data() {
return {
page:this.input
}
},
methods:{
handleChangeSize(input){
this.$emit('pageSize',input)
},
//上一页
prev(){
if(this.page>1){
this.page--
}else{
this.$message('这是首页哦!')
return false
}
this.$emit('pageSize',this.page)
},
//下一页
next(){
if(this.page<this.totalCount){
this.page++
}else{
this.$message('这是最后一页哦!')
return false
}
this.$emit('pageSize',this.page)
}
},
watch: {
input(val) {
this.page = val;
}
},
}
</script>
<style lang="scss">
.page{
i{
font-size: 20px;
vertical-align: middle;
color: #007DB5;
cursor: pointer;
}
.el-input{
width: 80px;
margin:0 8px;
.el-input__inner{
height: 30px;
text-align: center;
}
}
}
</style>
父组件
<template>
<div class="searchList">
<Page :totalCount="totalCount" :input="currentPage" v-on:pageSize="changPageSize"></Page>
</div>
</template>
<script>
import Page from "../../components/page.vue"
export default{
name:'searchList',
components: {
Page
},
data() {
return {
totalCount:1000,//数据总条目数
currentPage:1,//当前页
}
},
methods:{
...数据处理
changPageSize(){
...数据处理
},
}
}
</script>
<style lang="scss">
</style>