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:

https://i.sstatic.net/ZWMgx.png

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..)

https://i.sstatic.net/2j7HY.png

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

Using jQuery UI to create a bouncing effect on a CSS sprite image

Want to give your social icons a bounce effect using jQuery UI Bounce? I'm following a template and some jQuery documentation, but having trouble getting it right. It seems like the sprite image for the icons might be causing the issue. Can someone h ...

The POST request functions smoothly in Postman, however, encounters an error when executed in node.js

Just recently I began learning about node.js and attempted to send a post request to an external server, specifically Oracle Commmerce Cloud, in order to export some data. Check out this screenshot of the request body from Postman: View Request Body In Pos ...

Adjust the overflow to automatically decrease at regular intervals

Is there a way to make the scroll automatically move down a bit every few seconds, revealing more text in the process? Here's an example of how I want it to work: http://jsfiddle.net/Bnfkv/2/ ...

Why is it difficult to display data fetched through getJSON?

The test-json.php script retrieves data from the database and converts it into JSON format. <?php $conn = new mysqli("localhost", "root", "xxxx", "guestbook"); $result=$conn->query("select * From lyb limit 2"); echo '['; $i=0; while($row ...

Error: Namespace declaration does not have a type annotation - TypeScript/Babel

After creating my app using the command npx create-react-app --typescript, I encountered an issue with generated code and namespaces causing Babel to throw an error. Here are the steps I took to try and resolve the issue: I ejected the project Updated b ...

Slick Slider fails to load on web browsers

Hi everyone, I have a snippet of HTML code that I need help with: <!DOCTYPE html> <html> <head> <link rel="stylesheet" type="text/css" href="//cdn.jsdelivr.net/jquery.slick/1.6.0/slick.css"/> </head> <body> ...

Tips for arranging div elements in a grid-like matrix layout

I am facing a challenge in arranging multiple rectangular divs into a grid structure with 10 columns and 10 rows. The CSS styles for the top, bottom, left, or right positions must be in percentages to accommodate zoom in and out functionality without overl ...

Guide to organizing and performing operations within a loop using vue.js

I have an array called year-month-value containing data retrieved from a Google Sheet: 2019 - Mar - 3 2019 - Mar - 1 2019 - Feb - 1 2019 - Feb - 1 2019 - Feb - 1 2019 - Feb - 1 2019 - Feb - 3 2019 - Feb - 2019 - Feb - 2 2019 - Feb - 1 2019 - Feb - 1 2019 ...

What is the best way to arrange an array of objects in JavaScript by numerical order and then alphabetically?

Possible Duplicate: Sorting objects in an array by a field value in JavaScript I'm looking to sort an array of objects both numerically (by id) and alphabetically (by name). However, the current method I'm using is not giving me the desired ...

Tips on concealing and deactivating the fullscreen option in flowplayer

Could someone please assist me in resolving this issue? I've been attempting to hide the fullscreen button from the flowplayer, but so far, I haven't found a solution. Below is my JavaScript code: <script> $f("player", "flowplayer/flowpla ...

The function react__WEBPACK_IMPORTED_MODULE_0___default.a.useContext is not recognized when implementing Autocomplete within Material UI

Every time I attempt to create an Autocomplete tag utilizing Material UI, an error pops up, which can be seen in the following link: https://i.sstatic.net/kxKR4.png The Autocomplete code snippet is as follows: import React, {useState, useEffect, useCo ...

Transform PHP array into a JavaScript array

Currently, I am using Laravel and retrieving a list of values from a database with the following code: $idordenes = DB::table('ordenes')->select('id')->get(); Upon echoing the idordenes variable, the output is as follows: [{"fa ...

Gulp is ensuring the destination file remains unchanged

I'm encountering an issue with gulp in my project. I've set up a process to automate the compilation of source and styles into a single file using gulp. However, I'm facing a problem where it doesn't want to overwrite the `application.j ...

Incorporating AJAX in jQuery mobile to transmit data to a controller in CodeIgniter

I'm currently facing an issue where despite successfully retrieving the latitude and longitude values from the geolocation feature in Google Chrome, I am unable to pass these values to the index function within the controller named Add. When attemptin ...

Generate list items based on a PHP array using JavaScript

Upon fetching data from my database, I receive a PHP array structured as follows: $dbResult = array([0] => array([a] => 1 [b] => 1 [c] => 1) [1] => array([a] => 2 [b] => 2 [c] => 2) [3] => arr ...

Notify when the button value changes to "submit"

I recently added a jQuery form wizard to my website. I want users to receive an alert in JavaScript when they reach the end of the form. To achieve this, I inserted a simple JavaScript code at the beginning of my page within <head>..some code</hea ...

In Laravel, the page will be returned for any address except for those specified in the routes

I am looking to simplify the routing for my Laravel application. My goal is to have any request, regardless of how many slashes are included in the URL, return the same page as '/'. I want to avoid a 404 error and keep it as a valid route. /hell ...

Adjust the width of every column across numerous instances of ag-grid on a single webpage

I am facing an issue with Ag-grid tables on my webpage. I have multiple instances of Ag-grid table in a single page, but when I resize the browser window, the columns do not automatically adjust to the width of the table. We are using only one Ag-grid in ...

Utilizing React and Google Code to Enhance Lead Conversion Pages

I have developed a basic react application featuring a contact form. Upon submission, I aim to display the Google Code for the lead Conversion Page within the application. <!-- Google Code for Purchase Conversion Page --> <script type="text ...

Tips for dynamically adding an external SVG animation to your website:

When trying to insert an animated SVG using jQuery or plain JavaScript, they appear static in Chrome and Edge, but display correctly in Firefox: $(".loader").prepend("<svg><use xlink:href='/images/icons.svg#loading-ring'></use> ...