2

I have multiple views and I want to save state on each one, so the user doesn't have to do the same things again.

On one of them, I have a table and I use the bootstrap-pagination component for pagination, so when the user changes page, I send the request to a server for new data. I am storing sort and filter parameters in Vuex and it works well.

But when I want to save the current page like that, bootstrap-pagination changes it to 1 every time when I change view and go back. Is it possible to prevent that behavior?

Here is code in HTML:

<b-pagination v-if="currentPage!=-1"
            v-model="currentPage"
            :total-rows="totalRows"
            :per-page="perPage"
            aria-controls="my-table"
            pils
            align="center"
            class="ml-auto mr-auto"
          ></b-pagination>

and code in javascript:

  data: function () {
      return {
        ...
        currentPage: this.$store.state.currentPage,
        ...
      }
    },

    ...

    watch: {
        currentPage: function(){
                this.$store.commit('updateCurrentPage', this.currentPage);
                this.getData();
              },
    }

2 Answers2

5

The issues you're facing is most likely to do with the order of how your data is loaded and set.

When your component gets initialized, you set the currentPage page property immediately, while (I'm guessing) setting the totalRows property at some time later, after fetching your data from your database.

This causes issues because the pagination will think there's 0 rows. So when you set it to page 5. It will check the perPage and totalRows properties, and since there is no page 5 (yet), it will automatically set currentPage back to page 1.

Instead, i would recommend you set the currentPage to the value from your store AFTER you've retrieved your data and set the totalRows property. This should fix the issue you're experiencing.

Hiws
  • 8,230
  • 1
  • 19
  • 36
  • Damn that's unfortunate. Using your solution I set the `totalRows` first and then did a `this.$nextTick(() =>` and set my `currentPage` in the callback. And it works now. This seems like a bug, or at least a smell. – Abraham Brookes Jan 05 '22 at 03:45
  • The issue is absolutely related to the `totalRows` value. Thanks for your solution. – Babaktrad May 03 '22 at 09:54
2

Another work around is to put a v-if on the pagination element that checks that totalRows has been set. This causes the pagination element to be rendered after the totalRows value is known. It is useful when you are loading the data using AJAX and don't know the number of row ahead of time.

e.g.

<b-pagination
  v-if="totalRows > 0"
  v-model="currPage"
  :total-rows="totalRows"
  :per-page="perPage"
  aria-controls="my-table"
  size="sm"
  limit="7"
  first-number
  last-number
  >
</b-pagination>
Nick Falco
  • 207
  • 2
  • 10