3

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

julianstark999
  • 3,450
  • 1
  • 27
  • 41
TomHo
  • 33
  • 1
  • 4
  • Does this answer your question? [How to listen to the window scroll event in a VueJS component?](https://stackoverflow.com/questions/45822150/how-to-listen-to-the-window-scroll-event-in-a-vuejs-component) – thelr Jun 18 '20 at 12:16
  • That is scroll event, but what I want is detect scrollHeight value change. – TomHo Jun 18 '20 at 12:19
  • please share your code over jsfiddle or codepen – Mahamudul Hasan Jun 18 '20 at 12:26

1 Answers1

4

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;
    }
  }
})
Matt
  • 43,482
  • 6
  • 101
  • 102
  • 1
    I'm a little worry about performance issue, but it works! Thank you so much. – TomHo Jun 19 '20 at 14:58
  • why to use settimeout and lower perfomance if DOM API and gives you possibility to use `scroll` event? – Xth Nov 08 '21 at 16:28
  • @Xth this is about tracking scrollable height changes, not scroll position – Matt Nov 10 '21 at 16:58