We can add an infinite scrolling feature in our Vue app with the vue-infinite-scroll package.
To get started, we install the package by running:
npm install vue-infinite-scroll --save
The in main.js
, we register the plugin by writing:
import Vue from "vue";
import App from "./App.vue";
import infiniteScroll from "vue-infinite-scroll";
Vue.use(infiniteScroll);
Vue.config.productionTip = false;
new Vue({
render: h => h(App)
}).$mount("#app");
The infiniteScroll
package is registered with Vue.use
.
Then we can add infinite scrolling by writing:
<template>
<div id="app">
<div v-infinite-scroll="loadMore" infinite-scroll-disabled="busy" infinite-scroll-distance="10">
<p v-for="d of data" :key="d">{{d}}</p>
</div>
</div>
</template>
<script>
export default {
name: "App",
data() {
return {
data: [],
busy: false
};
},
methods: {
loadMore() {
this.busy = true;
setTimeout(() => {
this.data = [
...this.data,
...Array(50)
.fill()
.map(() => Math.random())
];
this.busy = false;
}, 1000);
}
}
};
</script>
We add the v-infinite-scroll
directive to a div.
The loadMore
method is run when we scroll to the bottom of the div to load more data.
loadMore
just adds more data into the data
array. The numbers are randomly generated and added.
We can set the infinite-scroll-disabled
prop to disable infinite scrolling if we have a given state.
infinite-scroll-distance
is the percent of the div that’s left to scroll before we trigger infinite scrolling.
Inside the div, we loop through the entries from the data
state.
Once we have that, then we can keep scrolling down to get more numbers in our numbers list.