vue添加滾動事件,解決簡書Carol_笑一笑方案中vue移除滾動事件失效的問題

在寫項目的時候,遇到了須要添加滾動事件的問題,在簡書Carol_笑一笑這裏找到了解決方案。代碼以下javascript

<script>
    export default {
      name:"vue-scroll",
      data () {
        return {
          ……
        }
      },
      mounted: function () {
        window.addEventListener('scroll', this.handleScroll, true);  // 監聽(綁定)滾輪滾動事件
      },
      methods: {
        handleScroll: function () {
            let clientHeight = document.documentElement.clientHeight || document.body.clientHeight;  
            // 設備/屏幕高度
            let scrollObj = document.getElementById(div); // 滾動區域
            let scrollTop = scrollObj.scrollTop; // div 到頭部的距離
            let scrollHeight = scrollObj.scrollHeight; // 滾動條的總高度
            //滾動條到底部的條件
            if(scrollTop+clientHeight == scrollHeight){
                // div 到頭部的距離 + 屏幕高度 = 可滾動的總高度
            }  
        }
      },
      destroyed: function () {
        window.removeEventListener('scroll', this.handleScroll);   //  離開頁面清除(移除)滾輪滾動事件
      }
    }
</script>

  可是在實際應用中,發現移除滾動事件失效了,到達新的頁面滾動事件還存在,從而致使一直報錯。而後從阮一峯先生的博文中找到了問題所在。html

而後上面的代碼只須要修改destroyed中的方法便可。vue

destroyed: function () {
        window.removeEventListener('scroll', this.handleScroll,true);   //  離開頁面清除(移除)滾輪滾動事件
}

  


返回目錄

相關文章
相關標籤/搜索