Vue結(jié)合better-scroll實現(xiàn)上拉加載(Vue3)
首先在mountedBScroll對象中注冊pullUpLoad,并設(shè)立在props內(nèi)部
this.scroll=new?BScroll(this.$refs.wrapper,{
??????click:true,
??????observeDOM?:true,
??????probeType:this.probeType,
??????pullUpLoad:this.pullUpload
????})
props:{
pullUpload:{
????type:Boolean,
????default:false
??}
}
其次監(jiān)聽pullingUp事件,并向父組件發(fā)射事件
this.scroll.on('pullingUp',()=>{
??????this.$emit('pullingUp')
?})
然后在scroll組件上編寫事件,并向子組件指定props內(nèi)容傳參
<scroll?class="wrapper"
?????????????????????ref="scroll"?
?????????????????????:probe-type="3"
?????????????????????:pullUpload="true"
??????????????????????@showposition="limitposition"
??????????????????????@pullingUp="loadMore"
??>
再然后回到首頁編寫指定函數(shù)
loadMore(){
????????this.getHomeGoods(this.currentGoodsType) //指定區(qū)域的上拉加載
??????????console.log("上拉加載更多");?
????}
到這里發(fā)現(xiàn),scrollheight還沒等圖片全部加載完就計算完成,導(dǎo)致我們滾動卡在一個位置,
這時我們就需要在圖片上監(jiān)聽它是否全部加載完成,別擔(dān)心,vue有自帶的事件-----load
在goodsListItem組件中
<template>
??<div?id="goodsListItem">
??????<img?:src="goodsListItem.show.img"?alt=""?@load="allImgLoad">
??????<div?id="info">
????????<p>{{goodsListItem.title}}</p>
????????<span>{{goodsListItem.price}}</span>
??????</div>
??</div>
</template>
在商品列表內(nèi)部編寫函數(shù)
methods:{
????allImgLoad(){
??????this.bus.emit('imgPartLoad')//調(diào)用事件總線方法
????}
??}
到這兒為止,有同學(xué)就會有疑問了,你這個bus是啥?
你先明白一個道理,有些組件與我們這個scroll組件并無關(guān)聯(lián),也就是不是父子組件的關(guān)系,那么它們也就做不到事件的發(fā)送和接收了,當(dāng)然了,你想通過vuex,指定一個內(nèi)容,通過它的變化來清楚一個事件的改變,莫不如用我們的事件總線。
在Vue2中,都是通過this.$bus.$emit('事件')還有this.$bus.$on('發(fā)送過來的事件',()=>{}),我們還需要在main.js中注冊實例對象
Vue.prototype.$bus=new Vue();
但是在Vue3.x以后從實例中移除了on,off和once 方 法,不過?emit 仍然是現(xiàn)有 API 的一部分,但也只能實現(xiàn)子組件觸發(fā)父組件的方法
此時就得依賴于mitt模塊
安裝方法:npm install --save mitt或者yarn add mitt -S
使用方法:
import?mitt?from?'mitt';
const?bus?=?mitt();
const?app?=?createApp(App)
installElementPlus(app)
app.config.globalProperties.bus?=?bus
app.use(store).use(router).mount('#app')
在首頁創(chuàng)建過程中接收事件
created:在模板渲染成html前調(diào)用,即通常初始化某些屬性值,然后再渲染成視圖。
mounted:在模板渲染成html后調(diào)用,一般是初始化頁面完成后,再對html的dom節(jié)點進(jìn)行操作
created(){
???this.getHomeData();
???this.getHomeGoods('pop');
???this.getHomeGoods('new');
???this.getHomeGoods('sell');
???this.bus.on('imgPartLoad',()=>{
?????this.$refs.scroll.scroll.refresh //這個寫在created中會出bug所以建議使用在mounted中
???});
??}
?mounted(){
???this.bus.on('imgPartLoad',()=>{
?????this.$refs.scroll.scroll.refresh
???});
??}
至此
