javascript - Vue 可以计算或观察 body 的 scrollHeight 吗?

标签 javascript vue.js vuejs2

我正在尝试使用 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

最佳答案

让计算属性返回 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;
    }
  }
})

关于javascript - Vue 可以计算或观察 body 的 scrollHeight 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62449695/

相关文章:

javascript - 阻止 ReSharper 将 JavaScript 函数参数放入新行

css - Vue 组件样式永不消失

vue.js - [BootstrapVue 警告] : popover - Unable to find target element in document

javascript - 将数据从表传递到模态形式

JavaScript - 用两根或更多手指滚动

javascript - 为什么使用discord.js 踢人不起作用

vue.js - 父子vue之间的异步生命周期

javascript - Vue JS动态添加子组件

javascript - 使用 Promise.all 获取基于名称的结果的最佳 es6 方法

vue.js transition css类无法放入单个文件组件