Mas cosas bonitas :3

This commit is contained in:
Daniel Cortés
2019-06-16 23:05:52 -04:00
parent a9838da2d7
commit c5ebe9599c

View File

@@ -1,49 +1,111 @@
<template> <template>
<div class="users"> <div class="users">
<div class="loading" v-if="loading">Loading...</div>
<div v-if="error" class="error"> <div v-if="error" class="error">
<p>{{ error }}</p> <p>{{ error }}</p>
<p>
<button @click.prevent="fetchData">
Try again
</button>
</p>
</div> </div>
<ul v-if="users"> <ul v-if="users">
<li v-for="{ name, email } in users"> <li v-for="{ name, email } in users">
<strong>Name:</strong> {{ name }}, <strong>Name:</strong> {{ name }},
<strong>Email:</strong> {{ email}} <strong>Email:</strong> {{ email}}
</li> </li>
</ul> </ul>
<div class="pagination">
<button :disabled="! prevPage" @click.prevent"goToPrev">Previous</button>
<button :disabled="! nexPage" @click.prevent"goToNext">Next</button>
</div>
</div> </div>
</template> </template>
<script> <script>
import axios from 'axios'; import axios from 'axios';
const getUsers = (page, callback) {
const params = page{ page };
axios
.get('/api/users', { params })
.then(response => {
callback(null, response.data);
}).catch(error => {
callback(error, err.response.data);
});
};
export default { export default {
data() { data() {
return { return {
loading: false,
users: null, users: null,
meta: null,
links: {
first: null,
last: null,
next: null,
prev: null,
},
error: null, error: null,
}; };
}, },
created() { computed: {
this.fetchData(); nextPage() {
if( !this.meta || this.meta.current_page === this.meta.last_page ) {
return;
}
return this.meta.current_page + 1;
},
prevPage() {
if( !this.meta || this.meta.current_page === 1 ) {
return;
}
return this.meta.current_page - 1;
},
paginationCount() {
if( !this.meta ) {
return;
}
const { current_page, last_page } = this.meta;
return `${current_page} of ${last_page}`
}
},
beforeRouteEnter(to, from, next) {
getUsers(to.query.page, (err, data) => {
next(vm => vm.setData(err, data));
});
},
beforeRouteUpdate(to, from, next) {
this.users = this.links = this.meta = null;
getUsers(to.query.page, (err, data) => {
this.setData(err, data);
next();
}
}, },
methods: { methods: {
fetchData() { goToNext() {
this.error = this.users = null; this.$router.push({
this.loading = true; query: {
axios page: this.nextPage,
.get('/api/users') },
.then(response => {
this.loading = false;
this.users = response.data.data;
}).catch(error => {
this.loading = false;
this.error = error.response.data.message || error.message;
}); });
},
goToPrev() {
this.$router.push({
name: 'users.index',
query: {
page: this.prevPage,
} }
});
},
setData(err, { data: users, link, meta }) {
if(err) {
this.error = err.toString();
} else {
this.users = users;
this.links = links;
this.meta = meta;
}
},
} }
} }
</script> </script>