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
1 Answer
Reset to default 4Having 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;
}
}
})