Last active
December 17, 2019 13:22
-
-
Save mohandere/3c879de253aa9d91057087ae297fe0db to your computer and use it in GitHub Desktop.
Infinite Loading with Vue.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<template> | |
<main class="container"> | |
<div> | |
<header> | |
<h3>Archives</h3> | |
</header> | |
<div v-if="posts && posts.length" class="postsList"> | |
<ul class="row"> | |
<li v-for="(post, index) in posts" class="postItem col-sm-4"> | |
<div class="postContent"> | |
<a :ref="index === 0 ? 'firstLink' : null" :href="post.URL | permalink" v-html="post.title" v-bind:class="{ active: getActiveClass(post.URL) }"> | |
</a> | |
<div class="post-meta">Posted on {{post.date | formatDate}} by <i>{{post.author.name}}</i></div> | |
</div> | |
</li> | |
</ul> | |
</div> | |
<ul v-if="errors && errors.length"> | |
<li v-for="error of errors"> | |
{{error.message}} | |
</li> | |
</ul> | |
<infinite-loading @infinite="infiniteHandler" spinner="bubbles"></infinite-loading> | |
</div> | |
</main> | |
</template> | |
<script> | |
import axios from 'axios' | |
import InfiniteLoading from 'vue-infinite-loading' | |
export default { | |
components: { | |
InfiniteLoading | |
} | |
data: () => ({ | |
perPage: 7, | |
currentPage: 1, | |
posts: [], | |
errors: [], | |
}), | |
methods: { | |
infiniteHandler ($state) { | |
let apiURL = `https://public-api.wordpress.com/rest/v1.1/sites/geekymohan.wordpress.com/posts/?number=${this.perPage}&page=${this.currentPage}` | |
axios.get(apiURL) | |
.then(response => { | |
let posts = response.data.posts | |
if (posts.length) { | |
this.posts = this.posts.concat(posts) | |
$state.loaded() | |
} else { | |
$state.complete() | |
} | |
++this.currentPage | |
}) | |
.catch(e => { | |
this.errors.push(e) | |
$state.loaded() | |
}) | |
} | |
} | |
} | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment