I am using VueJS and Vuetify.
In v-data-table UI Component of vuetify, I want to save the current page that the current user is. For example, if the user is on the page 3 of 10, and he reloads the page, it will automatically go back to page 3 of 10. The current function is when the user reloads, it goes back to page 1 of 10.
footerOptions: {
showFirstLastPage: true,
showCurrentPage: true,
itemsPerPageOptions: [20, 50, 100],
itemsPerPageText: 'Data per Page',
},
getPagination(data) {
sessionStorage.setItem('currentPage', data.page)
},
<v-data-table
:headers="tableHeaders"
:items="users"
item-key="username"
:loading="isLoading"
@item-selected="itemSelect"
@toggle-select-all="selectAll"
@click:row="singleClick"
@dblclick:row="doubleClick"
@pagination="getPagination"
:footer-props="footerOptions"
show-select
multi-sort
dense>
</v-data-table>
Edit: I am already getting the current page and save it to session storage. Now, all I need to make that currentPage binded in the v-data-table. I tried to used the page prop of v-data-table but nothing happens. Still on page 1 even the currentPage is 2/3/4 and so on.
CodePudding user response:
Here is what you should try:
add
:page
prop on v-data-table to bind the page number to a data propertypageNum
.listen for
update:page
event which fires from v-data-table any time the table's page value changes, then call a method namedpageChange
in the
pageChange
method you should save the page value (passed in for you by the event) to localStorage:localStorage.setItem("page", newPage);
on component creation, set
pageNum
to the value saved in localStorage:this.pageNum = localStorage.getItem("page");
simplified component code shown below:
<template>
<div>
<v-data-table
:headers="tableHeaders"
:items="users"
:page="pageNum"
@update:page="pageChange"
>
</v-data-table>
</div>
</template>
<script>
export default {
data() {
return {
pageNum: 1,
tableHeaders: [],
users: [],
};
},
methods: {
pageChange(newPage) {
localStorage.setItem("page", newPage);
},
},
created() {
this.pageNum = localStorage.getItem("page");
},
};
</script>
This will persist the page number value that v-data-table holds across page refreshes. You might want to think about clearing localStorage, localStorage.clear();
, when the user navigates to a different page so if they come back to the page with v-data-table they are on page 1 again.
CodePudding user response:
I think the issue may be that your users
is requested from backend?
You should change the value of pageNum
binded to v-data-table
after users
are got from remote.
<template>
<v-data-table
:items="users"
:page="pageNum"
>
</v-data-table>
</template>
<script>
export default {
data() {
return {
pageNum: 1,
users: [],
};
},
created() {
getUsers().then((promise)=>{
this.users = promise.data
this.pageNum = sessionStorage.getItem('currentPage');
})
},
};
</script>
The key point is that you should set the value of pageNum
when v-data-table
already has multiple pages.