手擼一個Vue滾動加載自定義指令
阿新 • • 發佈:2018-02-12
請求 tel document javascrip 決定 tlist win 滾動加載 pos
用Vue在移動端做滾動加載,使用mint-ui框架, InfiniteScroll指令loadmore組件,在uc瀏覽器和qq瀏覽器都無法觸發。無奈我只能自己寫了。
決定用vue 的自定義指令 寫滾動加載。
核心的api
- document.body.scrollTop 滾動條滾動的距離 (這個有兼容性問題,兼容性寫法)
let scrollTop = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop;
- window.innerHeight 瀏覽器窗口高度
- document.body.clientHeight 內容高度
思路給window綁定滾動事件,用 if(滾動條高度 + 瀏覽器窗口高度 >= 內容高度 - 閾值) 作為判斷條件。我們把自定義指令命名為 scroll
directives: { //滾動加載的自定義指令 scroll: { bind: function(el, binding, vnode) { window.addEventListener(‘scroll‘,()=> { let scrollTop = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop;if(scrollTop + window.innerHeight >= el.clientHeight - 50) { //判斷請求發送標誌位,避免重復請求 if(vnode.context.loading) return; //發送請求 vnode.context.getnewsData(); } }) } } },
有一個重點,因為發送請求的方法定義在了組件的methods中,在自定義指令裏,不能通過this拿到Vue實例,而是通過指令鉤子函數的第三個參數vnode的context屬性拿Vue的實例。
使用 時,直接給容器綁定v-scroll 指令即可
<template> <section v-scroll> <ul> <template v-for="data in data"> <li> .......... </li> </template> </ul> </section> </template>
手擼一個Vue滾動加載自定義指令