[Vuejs]-Why pagination with numbers is not working in Vue?

0👍

  1. You are not updating the page and limit in the Vuex store correctly. You are trying to commit the mutation with the wrong data. The limit and page are not part of the liveEvents.data object, they are part of the variables you sent in the query.

  2. You are not watching the Vuex store for changes in the events state. This means that when the events state changes, your component does not react to these changes.

  3. You are initializing posts in the data function and then pushing to it in the getPosts method. This is not reactive and Vue will not be able to track changes to posts.

Here’s how you can fix these issues:

  1. Update the fetchEvents action to commit the correct limit and page:
actions: {
  async fetchEvents({ commit, state }) {
    // ...
    commit('allEvents', response.data.liveEvents.data);
    commit("limit", state.limit),
    commit("page", state.page)
    // ...
  },
}
  1. Watch the Vuex events state in your component and update posts when it changes:
watch: {
  '$store.state.events': {
    handler: function(events) {
      this.posts = events;
    },
    immediate: true,
  },
  posts() {
    this.setPages();
  }
},
  1. Remove the getPosts method and the created lifecycle hook as they are not needed anymore.

  2. Initialize page to 1 instead of 0 in your Vuex store:

state: {
  limit: 12,
  page: 1,
  events: [],
},
  1. Update the paginate method to handle the case when page is 0:
paginate(posts) {
  let page = this.page;
  let perPage = this.perPage;
  let from = (page * perPage) - perPage;
  let to = (page * perPage);
  return page > 0 ? posts.slice(from, to) : [];
}
  1. Update the v-if condition in the Previous button to check if page is greater than 1:
<button type="button" v-if="page > 1" @click="page--"> Previous </button>

With these changes, your pagination should work correctly.

Leave a comment