Vue滾動加載自定義指令


用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.scrollHeight  內容高度 (兼容性寫法)
    let bodyHeight = document.body.scrollHeight ||  document.documentElement.scrollHeight;

思路給window綁定滾動事件,用  if(滾動條高度 + 瀏覽器窗口高度 >= 內容高度 - 閾值)  作為判斷條件。我們把自定義指令命名為 scroll

    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實例,而是通過指令鈎子函數的第三個參數vnodecontext屬性拿

必須要在unbind鈎子中解綁滾動加載事件,否則在其他頁面也會被觸發。

 

使用 時,因為基於文檔高度和滾動條高度,綁在哪里無所謂,這里綁定到容器上就可以了。

<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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM