先创建子组件
创建一个分页的子组件
<template>
<div>
<el-pagination
background
layout="prev, pager, next"
:page-size="5"
:total=totalPage
@current-change="callParentFunction($event)"
style="text-align: center;margin-top: 20px;"
>
</el-pagination>
</div>
</template>
<script>
export default {
name: 'v-bottomPage',
// 接受父组件的值,totalPage后台返回数据的总条数,
props: {
totalPage: Number,
required: true
},
data() {
return {
items:[]
}
},
created() {
},
methods:{
//子组件定义的方法
query(){
console.log('子组件中的方法:从父组件接收到的参数:'+this.totalPage);
},
// 子组件调用父组件的方法
callParentFunction(event){
this.$parent.fatherMethod(event);
}
},
}
</script>
<style>
</style>
父组件代码部分
<template>
<div class="app-container">
<div>这里是父组件</div>
<v-BottomPage
:totalPage="items.length"
>
</v-BottomPage>
</div>
</template>
<script>
import vBottomPage from '../../../components/bottomPage.vue'
export default {
components:{
vBottomPage
},
data() {
return {
items:[1,2,3,4,5,6,,4,8,,9,6,5],
};
},
created() {
},
methods: {
fatherMethod:function(event){
console.log('父组件中的方法: 当前点击的页数是'+JSON.stringify(event))
},
//父组件调用子组件的方法
fuzujian(){
this.$refs.child.query();
},
query:function(){
//模拟请求到数据,
this.items.concat([1,2,3,4,5]);
}
}
};
</script>
<style>
</style>
子组件通过 props接收父组件传的参数
props: {
//参数的名称,定义接收类型为数子
totalPage: Number,
required: true
},
父组件传递给子组件totalPage
<v-BottomPage :totalPage="items.length" > </v-BottomPage>
父组件调用子组件的方法
fuzujian(){
this.$refs.child.query();
}
子组件调用父组件的方法,这里总结了三种
1 常用的方法
this.$parent.fatherMethod();
2 方法是在子组件里用$emit向父组件触发一个事件,父组件监听这个事件就行了。
childMethod(){ this.$emit('fatherMethod'); }
3 父组件把方法传入子组件中,在子组件里直接调用这个方法
props: {
fatherMethod: {
type: Function,
default: null
}
},
childMethod() {
if (this.fatherMethod) {
this.fatherMethod();
}
}