Resetting the index and length in Vue.js each time a new page is loaded

Currently facing an unusual issue that I'm struggling to resolve. My goal was to include an index number in a for-each loop and calculate the total count of data within my vue.js component. While I successfully achieved this, I encountered a problem where the counter resets with each pagination page change, and items.length only reflects the data from the current pagination page. Here's what I've implemented:

<tr v-for="(item, index) in items" v-bind:key="item.id">
    <td>{{index + 1}}</td>
    <td>{{item.name}}</td>
</tr>

To get the total data count:

<div class="form-group">
    Total data: {{items.length}}
</div>

While everything works well on the initial pagination page, switching to the second page results in the total count only reflecting the data within that specific page, with the counter starting from 1 again. For example, on the first page it shows a total of 15 data entries (out of around 300), and the indexing is correct:

But upon moving to the second page, it continues to show the same total count, with the index starting from 1 once more instead of continuing consecutively (e.g., 16, 17..)

Snippet from the Vue.js component:

mounted() {
            this.getStatuses();
            this.getSchoolYears();

            if (this.items.length == 0) {
                this.loadPage(this.pagination.current_page);
                this.getObjects();
            }
        },
        methods: {
            getSaveStateConfig() {
                return {
                    'cacheKey': 'ApplicationComponent',
                };
            },
            addFilter(key, value) {
                this.filters = this.filters.filter(function (obj) {
                    return obj.key !== key;
                });
                this.pagination.current_page = 1;
                this.filters.push({key: key, value: value});
            },
            loadPageDebounce: _.debounce(function (page, parameters) {
                this.loadPage(page);
            }, 500),
            loadPage(page, parameters) {

                var parameters = '';
                this.filters.forEach(function (obj, index) {
                    parameters = parameters + '&' + obj.key + '=' + obj.value;
                });
                var $this = this;
                axios({
                    method: 'GET',
                    url: '/api/applications?page=' + page + parameters,
                    headers: {'X-CSRF-TOKEN': window.csrfToken, 'X-Requested-With': 'XMLHttpRequest'},
                })
                    .then(function (response) {
                        // console.log('resposne', response);
                        $this.items = response.data.data
                        $this.pagination.total = response.data.total;
                        $this.pagination.last_page = response.data.last_page;
                        $this.pagination.current_page = response.data.current_page;
                        $this.pagination.from = response.data.from;
                        $this.pagination.to = response.data.to;
                        $this.pagination.next_page_url = response.data.next_page_url;
                        $this.pagination.prev_page_url = response.data.prev_page_url;
                    })
                    .catch(function (error) {
                        console.log(error);
                    });
            },
            loadData() {
                this.loadPage(this.pagination.current_page, this.filters);
            },

Seeking advice on how to address this issue when using vue.js pagination. Thank you for any assistance provided.

Answer №1

Perhaps not the most optimal solution, but it should serve as a temporary workaround.

<tr v-for="(item, index) in items" v-bind:key="item.id">
    <td>{{(pagination.current_page*15)-15 + index+1}}</td>
    <td>{{item.name}}</td>
</tr>

Improved Solution with computed function for separating view and logic:

<tr v-for="(item, index) in items" v-bind:key="item.id">
    <td>{{getOverallIndex(index)}}</td>
    <td>{{item.name}}</td>
</tr>

computed: {
    getOverallIndex: function(index) {
      return this.pagination.current_page*15)-15 + index + 1
    }
  }

Answer №2

Within your method, it is important to note:

.then(function (response) {
         $this.items = response.data.data
         $this.pagination.total = response.data.total; // Point of interest

If your backend code is solid, you should receive the total count at this point.

As a troubleshooting step, consider using

console.log($this.pagination.total)
after this function or console.log(response.data.total) within the function. If you see 15 instead of 300, there might be an issue with your backend logic. It could be related to how this is bound in axios.

Please inform me if you discover any leads.

All the best!

Answer №3

give this a shot

<div v-for="(element, idx) in array" v-bind:key="element.id">
    <p>{{array.indexOf(element)+1}}</p>
    <p>{{element.title}}</p>
</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

When using Lockdown.js with NPM, I encounter a blank file being returned

When using Lockdown.js for NPM, I encountered an issue where the command to generate the lockdown file resulted in an empty file. Here are the links for the dependencies: NPM lockdown git Here is a snippet from my package.json: { "name": "nw", "pri ...

Using React to create an onScroll event listener within a mapped array

I am currently working on a setup where scrolling over an image mapped from an array updates the state with that image's coordinates, which in turn updates a Google Map. <CloudinaryContext cloudName="hcjmhcjf" fetchFormat="auto"> <div clas ...

Vue's watch feature will not execute if the watched property remains unchanged during a page reload

<template> <!-- The navbar has a property for gender, the color of the navbar will change depending on the gender --> <!-- pass the props gender through a form submission and event --> <div class="nav-main" :class="{f ...

Strategies for accessing the initial portion of an AJAX response

When using ajax to call an URL with dataType HTML, the response includes two parts such as accesstoken=1&expires=452. In this scenario, only the access token is needed. Using alert(response) displays both parts. How can the access token be extracted? ...

Tips on transferring a numerical ID variable from one page to another by clicking a link

I need help with passing a variable from an auto-generated button to another page when the button is clicked. The buttons all have the same link but different variables. How can I achieve this? Once I generate the button, I assign it a function like so: ...

conceal parent window element upon clicking an image within an iframe

I'm facing a challenge with hiding certain buttons in a parent window when opening a modal by clicking an image inside an iframe. Below is the code snippet that I am using: In the parent window - <iframe id="gallery" src="links/gallery.html" wid ...

Upgrade angular-chart.js when applied to a filtered collection

I recently started working with Angular and encountered an issue while incorporating Angular Charts JS. I have a list that can be filtered using search text, and I want my charts to update whenever the list is filtered. What would be the best approach to ...

Identify the difference between a regular function and a constructor in JavaScript

How can we determine whether a function in javascript is a simple, plain (anonymous) function, or a constructor (a function with a prototype)? I have developed the following function for this purpose: function checkFunctionType(value) { var ownPropert ...

Utilize CSS to vertically align buttons

One of my current projects involves creating a panel with buttons organized in columns side by side, similar to the layout shown below: However, I am struggling to achieve this desired arrangement. Below is the code I have been working on: <style&g ...

Utilize Function to Gain Access to React Context

As I work on developing a package that enhances the responsiveness of my React widget, I have encountered an issue. The responsiveness now relies not on the viewport width, but rather on the width of the widget container element. Presently, I am wrapping ...

Guide to importing Bootstrap 5 bundle js using npm

Having some issues with implementing Bootstrap5 and NPM. The website design is using bootstrap, which works fine, but not all the JavaScript components (dropdowns, modals, etc). I want to figure out how to import the Bootstrap JS bundle without relying on ...

When using JSON.stringify on a map object, it returns an empty result

var map1= new Map(); map1.set("one",1); var map2 = new Map(); map2.set("two",2); concatMap = {}; concatMap['one']= map1; concatMap['two']= map2; JSON.stringify(concatMap); //outputs : "{"one":{},"two":{}}" I als ...

Troubleshooting Problems with Promises in Node.js Express

I am currently developing a Node.JS/Express application with Jade as the template engine, but I am encountering some unexpected behavior. The issue arises when trying to retrieve data from a mock API and pass it to my Jade template. Despite confirming tha ...

AngularJS and synchronized queueing of API requests

I am attempting to develop a synchronized queue for API requests using AngularJS. class x { public y() { ... restRequest(); } } I have this class, along with a whiteboard canvas. When I drop an entity onto the canvas, the method &a ...

Is it possible to leverage specific client-side Javascript APIs on the server-side?

Exploring APIs designed for web browsers that require their .js code to return audio streams. In a broader sense, these APIs provide byte streams (such as audio) for playback in the browser. Is it possible to use these APIs in server-side Javascript frame ...

How to harness the power of loops in JavaScript

Having trouble getting this code to repeat a CSS transition properly. for (var i=0 ; i<4 ; i++){ setTimeout(function() { $('#top-left').css('margin', '45px 0 0 45px'); $('#top-mid' ...

Utilizing JSON strings within an onclick function

Hey there, currently I am working on sending an encoded JSON through the onclick attribute. However, I am facing a challenge because the JSON contains strings with a lot of apostrophes and quotes which end up closing the quotes in the onclick attribute. Up ...

What could be the reason for the Checkbox's value not showing up after making changes?

In my React and Material UI project, I am facing an issue where I want to check all checkboxes in a list by simply checking one checkbox in a parent component. Despite passing down the correct value of the parent checkbox through props, the visual changes ...

Continuously calling setState within the useEffect hooks causes an infinite loop

After extensive research and reading various articles on the topic, I am still facing the issue of infinite loops with useEffect and useState. One article that caught my attention was this one. Prior to reading the article, my useState function inside use ...

Utilizing Angular JS to parse JSON data and showcase it in various tables

Just diving into Angular JS and looking for some guidance. Can someone show me how to parse and showcase JSON Data in separate tables using Angular JS? [ { "id": 0, "isActive": false, "balance": 1025.00, "picture": "htt ...