【问题标题】:Can Vue computed or watch body's scrollHeight?Vue 可以计算或观察 body 的 scrollHeight 吗?
【发布时间】:2020-06-18 12:11:47
【问题描述】:

我正在尝试使用 computed 或 watch 来检测 body 的 scrollHeight 变化,但它不起作用。

这是我的代码:

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

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

CodePen 链接:https://codepen.io/chhoher/pen/wvMoLOg

【问题讨论】:

标签: javascript vue.js vuejs2


【解决方案1】:

让计算属性返回 document.body.scrollHeight 不会使其反应,您必须以另一种方式收听并通知 Vue 更改。

据我所知,了解 scrollHeight 已更改的唯一方法是对其进行轮询,因此您可以执行以下操作:

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;
    }
  }
})

【讨论】:

  • 我有点担心性能问题,但它确实有效!非常感谢。
  • 如果使用 DOM API,为什么要使用 settimeout 并降低性能并让您有可能使用 scroll 事件?
  • @Xth 这是关于跟踪可滚动高度变化,而不是滚动位置
猜你喜欢
  • 2020-11-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-20
  • 2011-06-17
  • 1970-01-01
  • 1970-01-01
  • 2014-10-29
相关资源
最近更新 更多