您的位置:首页 > Web前端 > Vue.js

vue 父组件调用子组件方法(适用于上拉加载loading开关的控制)

2018-12-05 15:21 1041 查看

1.父组件部分

<template>
<div>
<!-- :on-child-fun大写需要拆成 - 的形式,使用大写报错 -->
<v-child :on-child-fun="onChildFun"></v-child>
</div>
</template>
<script>
import child from './child'

export default {
components:{
'v-child' : child
},
methods:{
onChildFun(done){
//将子组件方法当做参数在父组件使用
console.log(done)
//done() 使用方法
}
}
}
</script>

2.子组件部分

<template>
<div>
<button @click="childBtn">我是组子组件,将方法传给父组件</button>
</div>
</template>
<script>
export default {
props: {
onChildFun: {
type: Function,
required: false
}
},
methods:{
childBtn(){
this.onChildFun(this.chilidFunction)
},
chilidFunction(){
this.loading = false
}
}
}
</script>

3.打印结果:

在实际的应用中,子组件点击执行应该换成页面滚动到底部执行

子组件部分实际使用思路
//滚动条距离页面顶部距离 + 滚动条高度 > 页面高度 (这样就表示页面到底部了)
if(scrollTop + scrollHeight > innerHeight ){
this.loading = true     //loading显示
this.onChildFun(this.chilidFunction)   //将关闭loading的方法传给父组件
}
chilidFunction(){
this.loading = false
}
父组件实际使用思路
onChildFun(done){
setTimeOut(()=>{
this.getData()//获取新的数据
done() //loading关闭
},800) //800是控制loading的显示时间
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: