Vue Js Pagination with Dotnet WebApi
To implement pagination in a Vue.js application that fetches data from a .NET Web API, you can use the following steps:
1. In your Vue component, create a data property to hold the current page number and page size, and a computed property to hold the data that is displayed on the current page.
data() {
return {
currentPage: 1,
pageSize: 10,
data: []
}
},
computed: {
currentData() {
return this.data.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize);
}
}
2. In the created() lifecycle hook, fetch the data from the API using axios or fetch API, and update the data property.
created() {
axios.get('/api/data?pageNumber=' + this.currentPage + '&pageSize=' + this.pageSize)
.then(response => {
this.data = response.data;
});
},
3. Create methods for handling the next and previous buttons and for changing the page size
methods: {
nextPage() {
if (this.currentPage < this.totalPages) {
this.currentPage++;
this.fetchData();
}
},
prevPage() {
if (this.currentPage > 1) {
this.currentPage--;
this.fetchData();
}
},
changePageSize(size) {
this.pageSize = size;
this.fetchData();
},
fetchData() {
axios.get('/api/data?pageNumber=' + this.currentPage + '&pageSize=' + this.pageSize)
.then(response => {
this.data = response.data;
});
}
}
4. In the template, create the pagination UI and use the properties and methods you created.
<template>
<div>
<div v-for="item in currentData" :key="item.id">
{{ item.name }}
</div>
<div>
<button @click="prevPage">Previous</button>
<button @click="nextPage">Next</button>
<select v-model="pageSize" @change="changePageSize">
<option value="10">10</option>
<option value="25">25</option>
<option value="50">50</option>
</select>
</div>
</div>
</template>
Note: The above example assumes that the Web API returns a JSON object that includes the data and the total number of records, and the client side uses this information to calculate the total number of pages. Also, you may need to adjust the code based on your specific requirements and the structure of your application.