最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Can Vue computed or watch body's scrollHeight? - Stack Overflow

programmeradmin1浏览0评论

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

Here is my code:

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

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

CodePen Link:

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

Here is my code:

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

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

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

Share Improve this question edited Jun 18, 2020 at 12:55 julianstark999 3,6141 gold badge30 silver badges42 bronze badges asked Jun 18, 2020 at 12:11 TomHoTomHo 331 silver badge4 bronze badges 3
  • Does this answer your question? How to listen to the window scroll event in a VueJS ponent? – thelr Commented Jun 18, 2020 at 12:16
  • That is scroll event, but what I want is detect scrollHeight value change. – TomHo Commented Jun 18, 2020 at 12:19
  • please share your code over jsfiddle or codepen – Mahamudul Hasan Commented Jun 18, 2020 at 12:26
Add a ment  | 

1 Answer 1

Reset to default 4

Having a puted 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
    }
  },

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

评论列表(0)

  1. 暂无评论