Looking to implement pagination in Vue.js - what steps should I take?

Hi there, I'm currently facing an issue while trying to paginate my data. The error message in my console reads:

Property or method "$index" is not defined on the instance but referenced during render.

Below is my HTML template where I display the data that I intend to paginate:

<div id="heroes">
      <table class="table table-striped">
        <thead>
          <tr>
            <td>Hero Name</td>
            <td>Universe</td>
          </tr>
        </thead>
        <tbody>
          <tr
            v-for="hero in heroes "
            v-show="setPaginate($index)"
          >
            <td>{{ hero.name }}</td>
            <td>{{ hero.universe }}</td>
          </tr>
        </tbody>
      </table>
      <div id="pagination">
        <a
          href="#"
          class="btn btn-default"
          v-for="page_index in paginate_total"
          @click.prevent="updateCurrent(page_index + 1)"
        >
          {{ page_index + 1 }}
        </a>
      </div>
    </div>

Here's my script tag for reference:


<script>
export default {
 
  data() {
    return {

      current: 1,
      heroes: [
        { name: "Wolverine", universe: "Marvel" },
        { name: "Batman", universe: "DC" },
        ...
      ],
      paginate: 5,
      paginate_total: 0
    };
  },
  created() {
    this.paginate_total = this.heroes.length / this.paginate;
  },
  methods: {
    setPaginate: function(i) {
      console.log(i);
      if (this.current == 1) {
        return i < this.paginate;
      } else {
        ...
      }
    },
    setStatus: function(status) {
      ...
    },
    updateCurrent: function(i) {
      ...
    },
    updatePaginate: function() {
      ...
    }
  }
};
</script>

I originally found this example on CodePen and it worked well there. Here is the link to the CodePen example:

https://codepen.io/lorena-tapia/details/VwZzpRZ

If anyone has any suggestions on how to resolve this issue, please let me know. Thank you!

Answer №1

The variable $index hasn't been defined anywhere; you can define it within the v-for loop like this:

<tr v-for="(hero,index) in heroes " v-show="setPagination(index)">
    <td>{{ hero.name }}</td>
    <td>{{ hero.universe }}</td>
</tr>

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

Discovering the process to create an onclick function with node.js code

index.html: <html> <h2>Welcome To User Profile Page !!!</h2> <button type="button">Edit Profile</button> <button type="button">Logout</button> </html> On my webpage, I have two buttons - Edit Profile and Lo ...

What is the best way to incorporate custom KnockoutJS functions using RequireJS?

I am facing an issue with my View Model that utilizes a custom observableArray function for sorting. The error message I receive states: "...has no methods 'sortByProperty'". How do I go about loading the handlers.js file to resolve this problem ...

Tips for accessing the content of a div tag with Protractor

Currently, I am working on developing a test that needs to click on a link within a div. However, there is an issue with my XPath locator due to some recent changes made by the developer in the UI. Using Xpath may not be a viable solution as the UI is subj ...

Have you ever encountered issues with Promises.all not functioning properly within your vuex store?

I'm currently experiencing an unusual problem. In my Vue project, I have a Vuex store that is divided into different modules. I am trying to utilize Promise.all() to simultaneously execute two independent async Vuex actions in order to benefit from th ...

Error: The prop type validation failed because a `value` prop was provided to a form field in React-Bootstrap-Typehead component

I am currently using the bootstrap-typehead package from https://github.com/ericgio/react-bootstrap-typeahead and struggling to understand why it's causing issues. Could someone help me identify what's wrong with this code that's triggering ...

Error encountered while trying to display content in the rendering area

const Pages = () => { return ( <> <Box display="flex"> {window.location.pathname === "/profile" ? undefined : <Sidebar />} <Box flex={3}> <Navbar /> <Routes> {/* Cont ...

What is the technique for adjusting the background while rotating the corner?

Is it possible to position a background image in the corner while rotating another image? rotate: $('#ship').css({ transform: 'rotate(' + corner + 'deg)' }); } move background: starx[i]=starx[i]+... s ...

The extent of utilizing the click handler in ECMA script 6

In ES6 arrow functions, the scope of this becomes available. However, there are instances where I cannot access this in an arrow function while it works with a normal anonymous function. For example: Sample 1 $(document).ready(function() { $(' ...

Vue3 TypeScript may potentially have an object that is 'undefined'

This piece of code is Vue3 with TypeScript-based. export interface TenantDto { uuid: string; name: string; } export const useTenantStore = defineStore('tenant', { state: () => ({ tenants: [], }), actions: { setMyTenants: (pa ...

How to display an element using an if statement in Next.js

I am attempting to incorporate a parameter into a nextJS component that will only display if a certain condition is met. At the moment, my code looks like this: return ( <div role="main" aria-label={this.props.title} classN ...

Implementing jQuery selector for CSS and properly handling special characters in the code

I've been attempting to use jQuery to change the background color of a radio button. I provided the CSS code below, but even after escaping special characters in jQuery as shown below, the solution still isn't working. #opt5 > [type="radio"]: ...

Discovering the Data Structures within the d3.js Illustrations by the Talented Mike Bostock

Wondering how to decipher the structure of JSONs in examples by Mike Bostock, like this one (after being transformed using d3): http://bl.ocks.org/mbostock/3886208 I aim to replicate it with my own fabricated array of JSON objects without relying on load ...

Using an outdated version of Node.js to set up a React App

Attempting to utilize Create React App but encountering an issue that demands Node 10 or above. Presently, my node version is Node 8.10.0 and unfortunately, I am unable to update the Node version as it's a work device. Is there a method to operate an ...

Error encountered when attempting to use the .save() method on a [mongoose_model_object] - the function contact.save is

In this scenario, the middleware 'auth' is responsible for generating a JWT and authorizing the user. I have also created a Mongoose model called Contact. However, when attempting to execute contact.save(), I encounter an exception stating that c ...

Create a dynamically updating list using React's TypeScript rendering at regular intervals

My goal is to create a game where objects fall from the top of the screen, and when clicked, they disappear and increase the score. However, I am facing an issue where the items are not visible on the screen. I have implemented the use of setInterval to d ...

The functionality of useMemo is compromised when changes are made to sessionStorage

I'm facing an issue with my app where the header contains an icon that should only be shown when the user is logged in. I store the login status in sessionStorage, but the component doesn't re-render when it changes. I attempted to use useEffect ...

Steps for pulling data from the Google Analytics query tool

I'm looking to retrieve my Google Analytics report using an API and save it locally. I've set up a Report in Google Analytics Explore, see attached image: https://i.sstatic.net/lkbKj.jpg From there, I can download the CSV file containing the da ...

Webpack is throwing an error due to the Vue component type being labeled as "any"

When using ts 4.2.4 and Vue3, I encountered a strange error while building my vue project: > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c3a2a7aeaaededb3a2a0a083f3edf2edf3">[email protected]</a> build > v ...

What is the best way to change the value of a div using JavaScript?

i could really use some assistance, i am trying to ensure that only the selected template is shown on the screen, while all others are hidden. The expected outcome should be to replace the values of: <div class="city">City<span>,< ...

What is the proper way to safely escape a JSON string for an object that contains user-generated content?

How can I correctly use the variable s for the value-field of an option-element while escaping user input used for key and value? var key='highway'; var value='track'; var s = JSON.stringfy({ [key]:value }, undefined,''); s ...