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

"Unlock the power of vue i18n pluralization with these step-by-step instructions

Below are some locale messages I have: timing: { viewer: { count: 'нету таймингов | 1 тайминг | 2 тайминга | 3 тайминга | 4 тайминга | {count} таймингов' } } Here is my template: < ...

The function was not invoked as expected and instead returned an error stating "this.method is not

I need help with an issue in my index.vue file. The problem lies in the fancy box under the after close where I am trying to call the messageAlert method, but it keeps returning this.messageAlert is not a function Can someone please assist me in resolving ...

Having trouble establishing a web socket connection using JavaScript

I'm experiencing an issue trying to connect my web socket to an Amazon instance using a specific IP address. I've had success connecting the web socket with a different IP and port using the Google Rest Client app, but now when I try to connect w ...

What is the reason for the lack of an applied CSS selector?

.colored p{ color: red; } article > .colored{ color:powderblue; } .blue{ color: white; } <!DOCTYPE html> <html lang="ko"> <head> <meta charset="UTF-8> <meta name="viewport" content="width=device-width, initi ...

Automating image uploads with Selenium and Python even when the element appears hidden

Recently, I've encountered an issue while trying to upload photos using Selenium with Python. The input element appears to be hidden on the page, causing errors when using the .sendkeys method. Here is the HTML code for the input element: <div d ...

Utilizing a combination of a `for` loop and `setInterval

I've been encountering an issue for the past 3-4 hours and have sought solutions in various places like here, here, here, etc... However, I am unable to get it to work in my specific case: var timer_slideshow = {}; var that, that_boss, has_auto, el ...

Make jQuery fire an event when the "enter" key is pressed

I'm trying to create an event that will trigger when the "enter" key is pressed. I've been using this code, but for some reason it's not working and I can't figure out why. After searching everywhere, I came across this snippet that see ...

Simple solution for storing key-value pairs temporarily in a form using JQuery

Is there an elegant method to temporarily store an array of string values in a form? In my article editing form, users can add tags as string values. I don't want these tags to be persisted until the user saves the entire article, so I require a way ...

Leveraging Vue properties within CSS styling

I am looking to utilize Vue data/prop variables within the <style> tag located at the bottom of my component. For example, suppose I have a component structured like this: <template> <div class="cl"></div> </template> < ...

Exploring the depths of JSON: Unraveling the secrets of reading dynamic object data

Currently, I am receiving a JSON file from another app and my goal is to parse it in order to extract the data contained within. The JSON includes user-defined dynamic data with changing key/value pairs, which has left me feeling uncertain about how to eff ...

Troubleshooting issues with Three.js and .obj file shadows

I've been diving into learning Thee.js, and while it's fairly straightforward, I've hit a roadblock with getting shadows to work. Despite setting castShadows, recieveShadows, and shadowMapEnabled to true in the appropriate places, shadows ar ...

Tips on utilizing the b-pagination API?

layoutchange() { this.layout = !this.layout; if (this.layout === true) { this.perPage = this.layout ? 8 : 12; this.listProducts(); } else { this.perPage = !this.layout ? 12 : 8; this.gridProducts(); } }, <a class="list-icon" ...

Is it possible to launch an Electron application by clicking a run button in the VSCode

I'm new to using VSCode and am currently working on an HTML5 app with Electron. I'm finding it cumbersome to switch between windows and enter a command each time I want to test my application. Is there a way to configure VSCode to run my Electron ...

Eliminate null objects from a JSON array with the help of GSON

{ "ChangeRequests": [ {} ] } Utilize Gson to remove the empty model from the JSON array. To achieve this, add a new model inside the list where all values are set to null using Gson. data class TestRequest( @SerializedName("ChangeRequests") val ...

What is the best way to transfer a JavaScript object to a VueJS component?

Even though it may seem like a basic question, I'm having trouble figuring out how to accomplish this in VueJS Here's the code I have in HTML: <script> var config = {'cols':4,'color':'red'} </script> ...

JavaScript now has Type Inference assistance

When attempting to utilize the Compiler API for processing JavaScript code and implementing Type inference to predict types of 'object' in a 'object.property' PropertyAccessExpression node, I encountered some issues. Some simple example ...

Error in Typescript occurrence when combining multiple optional types

This code snippet illustrates a common error: interface Block { id: string; } interface TitleBlock extends Block { data: { text: "hi", icon: "hi-icon" } } interface SubtitleBlock extends Block { data: { text: &qu ...

PHP code to store the start and end dates of a week in an array

Can someone help me with PHP code to format the start and end date of a week like this? Range: 16-Jan-2018 to 22-Jan-2018 I have the start and end dates, but I'm struggling to store them in an array for multiple weeks under one index. For example: ...

What is the procedure for configuring a proxy in Nuxt3?

Attempting to launch a Nuxt3 program, I am encountering issues with setting up a server proxy. When making a request to http://localhost:3000/api/v1, it is expected to return a response from our backend server located at . However, all I receive now is a 4 ...

Using Angular expressions, you can dynamically add strings to HTML based on conditions

I currently have the following piece of code: <div>{{animalType}}</div> This outputs dog. Is there a way to conditionally add an 's' if the value of animalType is anything other than dog? I attempted the following, but it did not ...