Reputation: 33
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
Upvotes: 3
Views: 8131
Reputation: 44078
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;
}
}
})
Upvotes: 4