Vue Communicates with the Internet Chapter 14
To know when the user has reached the bottom of the page, we add a method in our Vue
instance:
new Vue({
el: '#app',
methods: {
bottomVisible () {
const visibleHeight = document.documentElement.clientHeight
const pageHeight = document.documentElement.scrollHeight
const scrolled = window.scrollY
const reachedBottom = visibleHeight + scrolled >= pageHeight
return reachedBottom || pageHeight < visibleHeight
}
}
})
This will return true if either the page is scrolled until the bottom of the page itself is
smaller than the browser.
Next, we need to add a mechanism to bind the result of this function to a state variable
bottom and update it every time the user scrolls the page. We can do that in the created
hook:
created () {
window.addEventListener('scroll', () => {
this.bottom = this.bottomVisible()
})
}
The state will be composed of the bottom variable and the list of random words:
data: {
bottom: false,
words: []
}
We now need a method to add words to the array. Add the following method to the
existing method:
addWord () {
axios.get('http://www.setgetgo.com/randomword/get.php')
.then(response => {
this.words.push(response.data)
if (this.bottomVisible()) {
this.addWord()
}
})
}