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