简体   繁体   中英

Can Vue computed or watch body's scrollHeight?

I'm trying to use computed or watch to detect body's scrollHeight change, but it doesn't work.

Here is my code:

computed: {
    bodyScrollHeight() {
        return document.body.scrollHeight;
    }
},

watch:{
    bodyScrollHeight: function(newValue) {
        this.watchScrollHeight = newValue;
        this.myFunction(newValue);
    }
},

CodePen Link: https://codepen.io/chhoher/pen/wvMoLOg

Having a computed property return document.body.scrollHeight won't make it reactive, you have to listen to it another way and inform Vue of the change.

As far as I know, the only way to know scrollHeight changed is to poll it, so you could do something like:

new Vue({
  data: () => ({
    scrollHeight: 0,
    interval: null,
  }),

  mounted() {
    this.interval = setInterval(() => {
      this.scrollHeight = document.body.scrollHeight;
    }, 100);
  },

  destroyed() {
    clearInterval(this.interval);
  },

  watch: {
    scrollHeight() {
      // this will called when the polling changes the value
    }
  },

  computed: {
    doubleScrollHeight() {
      // you can use it in a computed prop too, it will be reactive
      return this.scrollHeight * 2;
    }
  }
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM