Creating pagination in Vue using an array of objects

I'm new to Vue and arrays and I need help paginating my json array so that only 10 items are displayed per page. Currently, all the items in the array are being shown in the <tr> body. I've tried different methods without success. Can someone assist me in finding the best way to paginate this json array and have it reflected in my table? Thank you.

Here is the code:

https://codesandbox.io/s/exciting-kapitsa-8d46t?file=/src/App.vue:1415-2437

App.vue

<template>
  <div id="app">
    <table class="table t3">
      <thead class="thead">
        <tr class="tr">
          <th class="td no" width="10%">
            <span class="has-text-orange">No</span>
          </th>
          <th class="td">
            <span class="has-text-orange">Name</span>
          </th>
        </tr>
      </thead>
      <tbody
        class="searchable tbody"
        style="max-height: 200px; min-height: 200px"
      >
        <tr class="tr" v-for="(p, index) in alphabets" :key="index">
          <td class="td no" width="10%">{{ ++index }}</td>
          <td class="td">{{ p.letter }}</td>
        </tr>
      </tbody>
    </table>
    <div class="column is-12">
      <nav
        class="pagination is-right"
        role="navigation"
        aria-label="pagination"
      >
        <ul class="pagination-list">
          <li>
            <a @click="prev"> Prev </a>
          </li>
          <li>
            <span
              class="pagination-link go-to has-text-orange"
              aria-label="Goto page 1"
              >{{ current }}</span
            >
          </li>
          <li>
            <a @click="next()"> Next </a>
          </li>

          <li>
            <input type="text" class="pagination-link" />
          </li>
          <li>
            <button class="button">Go</button>
          </li>
        </ul>
      </nav>
    </div>
  </div>
</template>

<script>
export default {
  name: "App",
  components: {},
  data() {
    return {
      current: 1,
      alphabets: [
        { letter: "a" },
        { letter: "b" },
        { letter: "c" },
        { letter: "d" },
        { letter: "e" },
        { letter: "f" },
        { letter: "g" },
        { letter: "h" },
        { letter: "i" },
        { letter: "j" },
        { letter: "k" },
        { letter: "l" },
        { letter: "m" },
        { letter: "n" },
        { letter: "o" },
        { letter: "p" },
        { letter: "q" },
        { letter: "r" },
        { letter: "s" },
        { letter: "t" },
        { letter: "u" },
        { letter: "v" },
        { letter: "w" },
        { letter: "x" },
        { letter: "y" },
        { letter: "z" },
      ],
    };
  },
};
</script>

<style>
#app {
  font-family: "Avenir", Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

Answer №1

Optimize your data loop by working with a smaller subset. Specify the page size by creating a pageSize property:

pageSize: 10

Determine the start and end indices of the reduced set based on the current page and page size:

computed: {
  indexStart() {
    return (this.current - 1) * this.pageSize;
  },
  indexEnd() {
    return this.indexStart + this.pageSize;
  },
},

Create another computed method to extract the reduced set from the boundaries:

paginated() {
   return this.alphabets.slice(this.indexStart, this.indexEnd);
}

Iterate through the reduced set instead of all the data entries:

v-for="(p, index) in paginated"

Below is an updated demo with adjustments for handling next and previous buttons when they exceed the available range:

new Vue({
  el: "#app",
  data() {
    return {
      current: 1,
      pageSize: 10,
      alphabets: [ ... ]
    };
  },
  computed: {
    indexStart() { ... },
    indexEnd() { ... },
    paginated() { ... }
  },
  methods: {
    prev() { ... },
    next() { ... }
  }
});
<div id="app">
    <table class="table t3"> ... </table>
    <div class="column is-12"> ... </div>

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

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

Trouble with Click event not working in Electron and mouse cursor not changing when hovering over an HTML button?

I'm in the midst of a project that involves using the electron framework. Within my project, I have an HTML file, a CSS file, and a Javascript file. The issue at hand is that when I hover over a button, the expected hand pointer icon fails to appear d ...

When attempting to capture an element screenshot as PNG, a TypeError occurs indicating that the 'bytes' object is not callable

Can someone please help me figure out how to save a screenshot of a specific element in Selenium using Python3? Here is the code I am trying: from selenium import webdriver import pyautogui as pog import time options = webdriver.ChromeOptions() options ...

I need to know how to use Axios to fetch data from multiple sources at the same time without any risk of the

Trying to initiate multiple axios operations simultaneously to fetch data from various sources at once using a loop leads to the received data getting intermingled and corrupted. Even creating distinct axios instances for each data source doesn't see ...

"Troubleshooting the lack of functionality in nested ajax calls, click events, or event

Initially, a navigation click event was created: $('#inner-navigation li a') .on('click', function (e) { e.preventDefault(); AjaxNavUrl.checkURL(this.hash); }); This event triggers an ajax call and respo ...

Tips for automatically closing SweetAlert after an AJAX request finishes

I recently implemented Sweet-alert into my Angular project. function RetrieveDataFromAPI(url) { SweetAlert.swal( { title: "", text: "Please wait.", imageUrl: "../../app/app-img/loading_spinner.gif", showConfirmB ...

Have you ever wondered why the React HeroIcons architecture includes React.createElement instead of simply returning plain SVG elements?

As I integrate HeroIcons into my Next.Js app, I find myself pondering over how they have structured their package architecture. The way they return icons is like this: const React = require("react"); function ArchiveIcon(props, svgRef) { retur ...

extract the text content from an object

I am trying to add an object to the shopping cart. The item contains a key/value pair as shown in the following image: https://i.stack.imgur.com/5inwR.png Instead of adding the title with its innerText using p and style, I would like to find another ...

Tips for utilizing MUI Typography properties in version 5

I'm clear on what needs to be done: obtain the type definition for Typography.variant. However, I'm a bit uncertain on how to actually get these. interface TextProps { variant?: string component?: string onClick?: (event: React.MouseEvent&l ...

Guide to automatically update mysql posts every second

Utilizing ajax, I am able to save user posts/comments into a mysql table without the need for a page refresh. Initially, there is this <div id="posts-container"></div> Next, I attempted to use Jquery load() to iterate through a table and disp ...

ES5 compatibility issue with Vue.js export default

I'm currently in the process of building a website, and I've decided to use Vue with ES5 for some parts. One issue I've encountered is trying to pass data from a child component in Vue back up to the parent. The solution proposed to me was ...

AngularJS, NodeJS, and Mongoose Challenge in Internet Explorer 11

I am currently working on developing my website using the AngularJS framework for the front end, Node.js for the backend, and Mongoose to store data in a MongoDB database. Everything works fine in Firefox RS v.24 and Chrome - when I add a new user to the ...

Saving maps on React Native can be done easily using AsyncStorage

I am facing an issue with saving user inputs as a JS map using AsyncStorage in my React Native app. Despite no errors during the saving process, I encountered "[object Map]" when attempting to retrieve the data. Here is a simplified version of my user map ...

Refresh the context whenever the state object changes

Within my application, I am utilizing a PageContext to maintain the state of various User objects stored as an array. Each User object includes a ScheduledPost object that undergoes changes when a user adds a new post. My challenge lies in figuring out how ...

In the JavaScript example provided, do child classes inherit their parent class prototype?

Here's the code I'm working with: class Rectangle { constructor(w, h) { this.w = w; this.h = h; } } Rectangle.prototype.area = function () { return (this.w * this.h); }; class Square extends Rectangle { construct ...

Exploring Angular14: A guide to efficiently looping through the controls of strictly typed FormGroups

Currently, I am working on upgrading my formGroups to be strictly typed in Angular v14. Within my FormGroup, there is a specific block of logic that iterates through all the controls and performs an action (this part is not crucial as I am facing issues be ...

Unlocking elements in Vue.js through functions

Looking to dynamically add a class to the label element when focusing on an input element below it. The current HTML and JS code I'm using is as follows: HTML: <label for="formProductId" ref="productIdLabel" class="form-element-title">Product ...

How come my invocation of (mobx) extendObservable isn't causing a re-render?

Can't figure out why the render isn't triggering after running addSimpleProperty in this code. Been staring at it for a while now and think it might have something to do with extendObservable. const {observable, action, extendObservable} = mobx; ...

Utilize the synchronization feature of ES6 Promises in Jasmine with the then/catch method

I have an angular controller that needs to be tested. This controller utilizes a service to fetch data from a server, and the service returns ES6 Promises. function MyController($scope, MyService) { $scope.doSomething = function () { MyService.foo() ...

The process of compressing font files (such as ArialMT.ttf) using JSZip is experiencing issues

While zipping images and HTML files works smoothly, I encountered an issue when trying to add font files for CSS. The font file is only 1kb in size, but it cannot be opened. Even after attempting to zip the font without any other files, the problem persis ...

Is it possible to add a jQuery-generated element to pure vanilla JavaScript?

I am facing a challenge in creating a new notification div when an event is triggered. Ideally, I would normally achieve this using jQuery by utilizing something like $("myDiv").append(newDiv). However, in this case, the item selector to which the new div ...