Skip to content

Instantly share code, notes, and snippets.

@itzikbenh
Created November 25, 2017 02:20
Show Gist options
  • Save itzikbenh/90918f44b3f871d206e6f5dddaabcc49 to your computer and use it in GitHub Desktop.
Save itzikbenh/90918f44b3f871d206e6f5dddaabcc49 to your computer and use it in GitHub Desktop.
import Vue from 'vue';
import posts from './components/posts.vue';
window.axios = require('axios');
window.Vue = Vue;
Vue.component('posts', posts);
const app = new Vue({
el: '#app',
});
<?php get_header(); ?>
<div id="app">
<posts></posts>
</div>
<?php get_footer(); ?>
<template>
<nav class="pagination">
<span class="page-stats">{{pagination.from}} - {{pagination.to}} of {{pagination.total}}</span>
<a v-if="pagination.prevPage" @click="$emit('prev')" class="button is-small pagination-previous">
Prev
</a>
<a class="button is-small pagination-previous" v-else disabled>
Prev
</a>
<a v-if="pagination.nextPage" @click="$emit('next')" class="button is-small pagination-next">
Next
</a>
<a class="button is-small pagination-next" v-else disabled>
Next
</a>
</nav>
</template>
<script>
export default {
props: ['pagination'],
}
</script>
<template>
<div>
<table class="table is-bordered">
<thead>
<tr>
<th>Title</th>
<th>Posted at</th>
</tr>
</thead>
<tbody>
<tr v-for="post in posts">
<td>{{post.title.rendered}}</td>
<td>{{post.date_gmt}}</td>
</tr>
</tbody>
</table>
<pagination :pagination="pagination"
@prev="--postsData.page; getPosts();"
@next="postsData.page++; getPosts();">
</pagination>
</div>
</template>
<script>
import pagination from './pagination.vue'
export default {
mounted() {
this.getPosts();
},
components: {
'pagination': pagination
},
data() {
return {
postsUrl: 'http://yourdomain/wp-json/wp/v2/posts',
posts: [],
postsData: {
per_page: 10,
page: 1
},
pagination: {
prevPage: '',
nextPage: '',
totalPages: '',
from: '',
to: '',
total: '',
},
}
},
methods: {
getPosts() {
axios.get(this.postsUrl, {params: this.postsData})
.then((response) => {
this.posts = response.data;
this.configPagination(response.headers);
})
.catch( (error) => {
console.log(error);
});
},
configPagination(headers) {
this.pagination.total = +headers['x-wp-total'];
this.pagination.totalPages = +headers['x-wp-totalpages'];
this.pagination.from = this.pagination.total ? ((this.postsData.page - 1) * this.postsData.per_page) + 1 : ' ';
this.pagination.to = (this.postsData.page * this.postsData.per_page) > this.pagination.total ? this.pagination.total : this.postsData.page * this.postsData.per_page;
this.pagination.prevPage = this.postsData.page > 1 ? this.postsData.page : '';
this.pagination.nextPage = this.postsData.page < this.pagination.totalPages ? this.postsData.page + 1 : '';
}
}
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment