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的顯示時間
}