用Vue在移動端作滾動加載,使用mint-ui框架, InfiniteScroll指令loadmore組件,在uc瀏覽器和qq瀏覽器都沒法觸發。無奈我只能本身寫了。
javascript
決定用vue 的自定義指令 寫滾動加載。html
核心的apivue
let scrollTop = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop;
let bodyHeight = document.body.scrollHeight || document.documentElement.scrollHeight;
思路給window綁定滾動事件,用 if(滾動條高度 + 瀏覽器窗口高度 >= 內容高度 - 閾值) 做爲判斷條件。咱們把自定義指令命名爲 scrolljava
directives: { /** * 滾動加載的自定義指令 */ scroll: { bind: function (el, binding, vnode) { window.addEventListener('scroll', vnode.context.scrollLoad) },
//路由轉跳到其餘頁面時,會調用unbind,解綁滾動加載事件。 unbind: function (el,binding, vnode) { window.removeEventListener('scroll', vnode.context.scrollLoad) } } }, methods: { scrollLoad() { //滾動條高度(頁面被捲去高度) let scrollTop = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop; //文檔高度 let bodyHeight = document.body.scrollHeight || document.documentElement.scrollHeight; if (scrollTop + window.innerHeight >= bodyHeight - 50) { //判斷請求發送標誌位,避免重複請求(這個須要本身在data裏聲明,直接貼代碼會報錯。默認爲false,發送請求前改成true, 請求完成回調函數裏改回false) if (this.loading) return; //發送請求 this.getnewsData(); }, getnewsData() {/*發送請求的函數*/} },
有一個重點,由於發送請求和滾動事件的方法定義在了組件的methods中,須要拿到Vue實例,但在自定義指令裏,不能經過this拿到Vue實例,而是經過指令鉤子函數的第三個參數vnode的context屬性拿node
必需要在unbind鉤子中解綁滾動加載事件,不然在其餘頁面也會被觸發。api
使用 時,由於基於文檔高度和滾動條高度,綁在哪裏無所謂,這裏綁定到容器上就能夠了。瀏覽器
<template> <section v-scroll> <ul> <template v-for="data in datas"> <li> .......... </li> </template> </ul> </section> </template>
以上內容,轉載請註明出處 https://www.cnblogs.com/lijinwen/p/8444400.html框架