A guide to implementing accurate pagination in Vue.js 2

I'm encountering an issue while setting up pagination with Vue. My goal is to load new tasks from jsonplaceholder when the numbers on the buttons are clicked.

I have managed to successfully load the first and second pages. I believe this is directly related to my this.fetchTodos() action. Being a beginner in Vue, I am seeking assistance in understanding how to update the data when transitioning to a new page without triggering a reload.

In this scenario, it is important for the URL of the page to change (GET request). While the page state changes, the posts do not load upon clicking on the third page.

Below, I have included the code snippets from four files which should provide insight into the current situation.

If it helps, you can also refer to the GitHub link and review the pagination branch.

Thank you in advance for your support! Feel free to leave any questions or requests for more information in the comments section.

The files include:

1. TodoListView.vue - the starting page where todos are fetched and displayed

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<template>
<div class="todolist">
... (Vue template code)
</template>

... (Vue script code)

2. TodoListPaginationView - loads the second page and subsequent pages upon pagination click

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<template>
<div class="todolist">
... (Vue template code)
</template>

... (Vue script code)

3. PaginationBootstrap.vue - contains the logic for pagination using UI Bootstrap 5 components

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<template>
... (Vue template code)
</template>

... (Vue script code)

4. todosModule.js - includes Vuex logic for managing todos

import axios from "axios";
export const todosModule = {
    state: () => ({
        // State properties and mutations
    }),
    mutations: {
        // Mutations for updating state
    },
    actions: {
        // Actions for asynchronous operations
    },
    getters: {
        // Getters to retrieve computed state values
    },
    namespaced: true
}

Answer №1

Alright, I've managed to discover a solution on my own.

The key element here is the watcher. In TodoListPaginationView.vue, I included the following code:

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<template>
<div class="todolist">
  <ContainerBootstrap>
    <div class="row">
      <div class="col-12 text-center">
        <TitlePage :text="'Страница №'+ page"/>
        <router-link to="/todolist">
          <button-bootstrap css-class="btn-lg btn-primary mt-2 mb-4">Back to Top</button-bootstrap>
        </router-link>
      </div>
      <TodoList v-if="todos" :todos="searchedTodos"/>
      <PaginationBootstrap :page="page" :total-pages="totalPages" class="mt-4"/>
    </div>
  </ContainerBootstrap>
</div>
</template>

<script>
import ContainerBootstrap from "@/components/UI/ContainerBootstrap";
import TitlePage from "@/components/TitlePage";
import ButtonBootstrap from "@/components/UI/ButtonBootstrap";
import TodoList from "@/components/TodoList";
import {mapActions, mapGetters, mapMutations, mapState} from "vuex";
import PaginationBootstrap from "@/components/UI/PaginationBootstrap";
export default {
  name: "TodoListPaginationView",
  components: {PaginationBootstrap, TodoList, ButtonBootstrap, TitlePage, ContainerBootstrap},
  methods: {
    ...mapActions({
      fetchTodos: "todos/fetchTodos",
    }),
    ...mapMutations({
      setSearchQuery: 'todos/setSearchQuery'
    })
  },
  computed: {
    ...mapState({
      todos: state => state.todos.todos,
      isTodosLoading: state => state.todos.isTodosLoading,
      page: state => state.todos.page,
      limit: state => state.todos.limit,
      totalPages: state => state.todos.totalPages,
      searchQuery: state => state.todos.searchQuery
    }),
    ...mapGetters({
      searchedTodos: 'todos/searchedTodos'
    })
  },
  watch: {
    page: function (val) {
      if (val) {
        this.fetchTodos()
      }
    },
  },
  mounted() {
    this.fetchTodos();
  },
}
</script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the solution to the problem of "Failed to execute 'json' on 'Response': body stream already read"?

enter image description here Encountered Issue: Error in processing JSON data in the Response: body stream already read The error mentioned above is a result of issues within your application's code, not due to Cypress. It occurred due to an unhandle ...

Arranging DIVs in a vertical layout

Currently, I am working on a design that involves organizing several <DIV> elements in a vertical manner while still maintaining responsiveness. Here are some examples: Wider layout Taller layout I have tried using floats, inline-block display, ...

Using AngularJS to toggle between two select dropdowns

I have two drop-down lists containing JSON data. <select class="form control" ng-model="fruitsName" ng-options="r.id as r.name for r in fruits"> <option value="">--Select---</option></select> $scope.fruits = [{'id': &apo ...

Leveraging External Scripts with Vue.js and Laravel: A Comprehensive Guide

I am new to using vue js and laravel mix, and I am facing some confusion. Previously, I manually loaded scripts without compiling them. However, now that I want to integrate vue js into my project, adding the app.js script at the end of my blade template c ...

When I use .fadeToggle, my div transitions smoothly between visible and hidden states

Looking to create a sleek navigation menu that showcases a colored square when hovered over? I'm currently experiencing an issue where the squares are not aligning correctly with the items being hovered. Switching the position to absolute would likely ...

How can AngularJS apps handle authentication?

Seeking input on user authentication with AngularJS and Zend... I currently have Angular on the client side and Zend on the server side handling authentication successfully. However, I'm looking for best practices and code examples for enhancing the ...

"Interactive Connect 4 Game in Javascript - Drop the disk into the bottom row of the chosen

Check out this awesome Connect4 game I found: http://codepen.io/anon/pen/lmFJf I have a specific goal in mind for the game. When I click on an empty space in any column, I want it to automatically drop into the lowest available spot in that column, follow ...

Mastering the art of navigating through multiple nested objects is achievable by harnessing the power of recursive

I'm utilizing the AngularTree directive in my Angular application to display a tree view of a specific data structure. The data structure can be viewed at https://jsfiddle.net/eugene_goldberg/Lvwxx629/17/. You can find more information about the Angul ...

What is the method to obtain an object as the return value from a click function in JavaScript?

I would like to retrieve the cell value from a table by clicking on a button. I have already created a function called getDetail in JavaScript that is implemented on the button, but I am facing difficulty in returning the value from the function. <butto ...

jQuery will envelop the HTML elements in an inconsequential div

Imagine a website that is visually complex, with various styles and images positioned in different ways. What if we wanted to add a small overlay icon above each image? At first, the solution might seem simple - just use absolute positioning for a span el ...

How to make text dynamically shrink with TailwindCSS class 'flex-shrink-0'

I've designed an 'Album' (React) component to showcase album artwork, name, and release date in a card-like format. This component consists of two divs - one for the photo and the other for text. Each artist's discography displays multi ...

Tips for showing a single table with buttons on display

I am using R markdown and have included multiple tables with buttons, but when I open the file, all tables are displayed at once. How can I ensure only one table is shown upon opening the file? https://i.sstatic.net/NFidf.png <script type="text/ja ...

Was not able to capture the reaction from the Angular file upload

I've been attempting to upload a single file using the POST Method and REST Calling to the server. Despite successfully uploading the module with the code below, I encounter an error afterwards. Is there anyone who can lend assistance in troubleshooti ...

Using JavaScript, extract the most recent 10 minutes worth of UNIX timestamps from a lengthy array

I am working with an array that contains multiple UNIX timestamps and I need to retrieve the timestamps from the last 10 minutes. Specifically, I only require the count of these timestamps, possibly for a Bot protection system. Would it be best to use ...

The `process` variable is not recognized in a Vue/TypeScript component

I've encountered an issue trying to use .env variables in my Vue app. When I ran npm install process, the only syntax that didn't result in an error when importing was: import * as process from 'process'; Prior to this, I received the ...

Enhancing JavaScript Asynchronous Programming with EventLoop and async/await

Exploring the intricacies of how JavaScript processes asynchronous methods led me to dive into async/await. In an effort to gain a complete understanding, I crafted the following example: async function first() { console.log(9); await Promise.resolv ...

Can Django implement pagination without altering the URL structure?

I discovered the fundamentals of pagination in Django at this resource: Nevertheless, I am faced with a challenge - I wish to implement pagination without modifying the URL. Specifically, I need to paginate a single table among multiple tables on an HTML ...

Bidirectional Data Binding Using Meteor and React

When using Meteor, the getMeteorData() method is preferred over getInitialState(). But how can we achieve binding, especially with regards to a user's surname in their profile? ... getMeteorData() { return { u = Meteor.user() } }, componentRen ...

What is the best way to create a JavaScript Up/Down Numeric input box using jQuery?

So, I have this Numeric input box with Up/Down buttons: HTML Markup: <div class="rotatortextbox"> <asp:TextBox ID="txtrunningtimeforfirstlot" ClientIDMode="Static" runat="server">0</asp:TextBox> (In mins) </div> <div cl ...

Is there a way to calculate the number of days between two selected dates using the bootstrap date range picker?

I recently implemented the bootstrap daterange picker for selecting start and end dates, and it's been working perfectly. However, I now have a requirement to display the count of days selected. Here's my current code: $('input[name="datera ...