vue如何正確銷毀當前組件的scroll事件?


將方法寫出來,銷毀在beforeDestroy寫。

mounted(){
  window.addEventListener("scroll",this.handleFun),
},
methods:{
  handleFun(){
    let t = document.documentElement.scrollTop || document.body.scrollTop;
      let tabBar = document.getElementById("tabBar");
      if( t >= 88 ) {
        tabBar.style.cssText="position:fixed;top:0;z-index:999";
      } else {
        tabBar.style.position="relative";
      }
  }
},
beforeDestroy(){
  window.removeEventListener("scroll",this.handleFun)
}

以下幾種方法同樣有效:

//把scroll的匿名函數掛到this上

mounted(){
      this.tabScroll();
    },
methods:{
  tabScroll(){
      this.scroll_ = function () {
        let t = document.documentElement.scrollTop || document.body.scrollTop;
        console.log(t);
        let tabBar = document.getElementById("tabBar");
        if( t >= 88 ) {
          tabBar.style.cssText="position:fixed;top:0;z-index:999";
        } else {
          tabBar.style.position="relative";
        }
      }
      window.addEventListener("scroll",this.scroll_);
    },
},
destroyed(){
      window.removeEventListener("scroll",this.scroll_);
    }
methods:{
  tabScroll(){
      window.addEventListener("scroll",this.handleScroll);
  },
  handleScroll(){
        let t = document.documentElement.scrollTop || document.body.scrollTop;
        console.log(t);
        let tabBar = document.getElementById("tabBar");
        if( t >= 88 ) {
          tabBar.style.cssText="position:fixed;top:0;z-index:999";
        } else {
          tabBar.style.position="relative";
        }
  }
},
mounted(){
      this.tabScroll();
},
beforeDestroy(){
    window.removeEventListener("scroll",this.handleScroll);
}

這里有一點需要注意:

給vue組件綁定scroll事件,如果直接在 mounted鈎子中寫window.addEventListener("scroll",handleFun()),
則頁面並不會執行scroll事件,原因如下:

  1. 要銷毀handleFun的話,得把handleFun寫在method
  2. 應該是window.addEventListener("scroll",this.handleFun)window.removeEventListener("scroll",this.handleFun),  
  3. 而不是window.addEventListener("scroll",this.handleFun())window.removeEventListener("scroll",this.handleFun())

第二個參數應該是一個function,而不是執行它。

 

感謝各位朋友的指導~


免責聲明!

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



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