在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/Java  HTML/ vue中添加一個返回頂部按鈕,切換頁面后一直報錯,什么原因呢

vue中添加一個返回頂部按鈕,切換頁面后一直報錯,什么原因呢

在首頁中加入了一個返回按鈕的BackToTop組件,并在mounted()中監(jiān)聽scrollTop,如果scrollTop大于0,組件就顯示,否則隱藏。
backToTop代碼如下:

<template>
  <span 
    tabindex="0" 
    class="iconfont" 
    title="返回頂部" 
    @click="handleToTop"
    @blur="BlurOrScroll"
    ref="toTop"
  >&#xe6c2;</span>
</template>

<script>
export default {
  name: 'BackToTop',
  data() {
    return {
      isToTop: false, //是否點擊了返回頂部
      isStop: false, //返回頂部過程中是否要暫停
      scrollTimer: null,
      showTimer: null
    }
  },
  methods: {
    // 按鈕失去焦點后觸發(fā),停止?jié)L動
    BlurOrScroll() {
      if(this.isToTop) {
        this.isStop = true;
      }
    },
    // 點擊按鈕后觸發(fā),回到頂部
    handleToTop() {
      this.isToTop = true;
      let scrollDist = 0;
      let speed = 0;
      this.scrollTimer = setInterval(() => {
        scrollDist = document.documentElement.scrollTop || document.body.scrollTop;
        speed = Math.floor(-scrollDist/6);
        if(scrollDist !== 0 && !this.isStop) {
          scrollDist = scrollDist + speed >= 0 ? scrollDist + speed : 0;
          document.documentElement.scrollTop = document.body.scrollTop = scrollDist;
        } else {
          clearInterval(this.scrollTimer);
        }
      },20);
    },
    //控制組件的顯示和隱藏,當(dāng)頁面有滾動時顯示
    showOrHide() {
      if(this.showTimer) {
        this.showTimer = null;
      }
      this.showTimer = setInterval(() => {
        let windowH = document.documentElement.clientHeight || document.body.clientHeight;
        if(document.documentElement.scrollTop || document.body.scrollTop >= windowH) {
          this.$refs.toTop.style.display = 'block';
        } else {
          this.$refs.toTop.style.display = 'none';
        }
      },30);
    }
  },
  watch: {
    isStop() {
      clearInterval(this.scrollTimer);
      this.isStop = false;
    }
  },
  mounted() {
    window.addEventListener('scroll',this.showOrHide,true);
  }
}
</script>

<style lang="stylus" scoped>
  .iconfont
    display none
    position fixed
    right .5rem
    bottom 1rem
    height .6rem
    width .6rem
    font-size .8rem
    cursor pointer
    outline none
</style>

在首頁功能正常,但切換頁面后BackToTop持續(xù)報錯,截圖如下:

clipboard.png

在另一個頁面中并沒有添加BackToTop組件,為什么會報錯呢?求解

回答
編輯回答
離觴

setInterval要用clearInterval才能停止,你沒有停止的話內(nèi)部還是在持續(xù)循環(huán),頁面切換后的$refs.toTop為空,后繼調(diào)用自然出錯了。
話說你這個需求監(jiān)聽scroll完全夠了,用setInterval是多此一舉

2017年3月26日 06:38
編輯回答
紓惘

事件監(jiān)聽是在window上的,在離開時需要在destroyed時進行clearInterval(this.scrollTimer)

2017年8月15日 07:56
編輯回答
半心人

單頁面引用只是頁面內(nèi)容變了,其實全局的變量什么的都還在。
所以你全局的setInterval還在繼續(xù)跑,windowonscroll也還在繼續(xù)跑。

但是你ref的資源沒在了。所以就報錯了

2018年8月10日 03:03
編輯回答
尋仙

那是因為你scroll事件監(jiān)聽是在window上面監(jiān)聽的,所以離開頁面要移除事件監(jiān)聽就好了

2018年2月27日 20:24