Guide to VueJS: Implementing pagination in v-for to display 10 items on each page

I am struggling with displaying 10 questions at a time from a questionnaire that contains a total of 60 questions.

Despite finding some references online, I am having difficulty getting it to work properly.

The issue I am facing is that when I click on next(), 10 new items are added to the v-for but the previous 10 items still remain on the page.

Here is my current implementation:

<div class="test-questions comp">
                    <div class="question" v-for="q in perguntas['questions']" v-if="q.id <= perpage">
                        <div class="statement">
                            {{q.id}}. {{q.text}}
                        </div>
                        <div class="options yes-no">
                            <div class="caption option yes">Yes</div>
                            <div class="caption option no">No</div>
                        </div>
                    </div>
                  
                </div>
                <div class="action-row">
                    <button v-if="perpage == 60" @click="salvarRelato()"><span>Publish</span></button>
                    <button v-if="perpage < 50" @click="previous()"><span>Previous</span></button>
                    <button v-if="perpage < 50" @click="next()"><span>Next</span></button>
                </div>

This is how I have structured my data:

props: ['perguntas'],
        data(){
            return {
                perpage: 10,
            }
        },
        methods: {
            next(){
                this.perpage = this.perpage + 10;
            },
            previous(){
        this.perpage = this.perpage - 10;
            },
        }

Any assistance would be greatly appreciated!

Answer №1

Consider incorporating a new attribute named pageNumber, starting with the value of 1. Then, utilize another attribute defined as a computed property known as currentPageItems, which relies on pageNumber and perPage. Proceed to iterate through the currentPageItems:

props: ['queries'],
        data(){
            return {
                perpage: 10,
                pageNumber:0
            }
        },
      computed:{
        currentPageItems(){
          return this.queries.slice(this.pageNumber*this.perpage,this.pageNumber*this.perpage+1+this.perpage)
        }
         }
        methods: {
            next(){
                this.pageNumber++;
            },
            previous(){
           this.pageNumber--;
            },
        }

template :

   v-for="q in currentPageItems"

Answer №2

To efficiently render questions in Vue, you can create an array to store the questions that need to be displayed. Whenever the loadnext() method is triggered, this array can be populated with 5 new questions while clearing out the old ones.

Take a look at this Live Demo

Here's the snippet for Vue markup:

<template>
   <div id="app">
      <div v-for="item in toRender" :key="item" > {{ item.name }} </div>
      <button @click="loadnext()">Next</button>
   </div>
</template>

And for Vue <script>:

data: () => ({
  start: 0, // Starting index
  end: 5, // Ending index
  questions: [], // Array of all questions
  toRender: [] // Array of questions to be rendered 
}),

mounted() {
  for (let i = this.start; i < this.end; i++){
    this.toRender.push(this.questions[i])
  }
  this.start = this.start + this.toRender.length;
  this.end =  this.start + this.toRender.length;
}

methods: {
  loadnext() {
    this.toRender = [];
      for (let i = this.start; i < this.end; i++){
        this.toRender.push(this.questions[i])
      }
   }
 } 

Answer №3

Consider implementing a system with two arrays, primary and secondary, to optimize the retrieval process when using the next() method. Retrieve 10 items from the primary array each time next() is called and add them to the secondary array. Utilize v-for on the secondary array to display all items, including both previous and newly added ones.

While there may be alternative methods for accomplishing this task more efficiently, I can currently only recommend this solution as a temporary measure.

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

Issue with Vue js template not correctly binding class properties

Struggling with a code example available at: https://v2.vuejs.org/v2/guide/class-and-style.html Here is a simplified version of my code snippet: var classdata = { "isActive": false } Vue.component('app&a ...

A guide to creating a reference between two tables using the hasOne method in sequelize.js

After generating 3 models using sequelize-auto, let's take a look at them: sequelize.define('users', { id: { type: DataTypes.INTEGER, allowNull: false, primaryKey: true, autoIncrement: ...

What is the process for using the fetch method in React to upload a file?

Currently, I am developing a react component that involves uploading an Excel file to a server. Although my approach seems correct, it returns an empty object when I check the request body in console. <input type="file" id="avatar" name="avatar" onChan ...

Even after unsubscribing with mqtt.js, the old listener continues to receive messages

Currently, I am utilizing mqtt.js to receive websocket data from an MQTT server. The subscription process is functioning properly, but the challenge lies in changing the topic dynamically by modifying the websocket configuration. The issue arises when, eve ...

Arranging object arrays according to strings

Imagine there is an array: var a = [ { name: 'Tom', surname: 'TestAsIvanov' }, { name: 'Kate', surname: 'Ivanova' }, { name: 'John', surname: 'Alivanov' }, { name: 'Ivan&apos ...

Is the z-index feature not functioning as anticipated?

I'm currently working on a project involving a book that flips on click on both sides. The process involves checking the direction when a page is clicked and flipping it to the left if it's not to the right. Additionally, I adjust the z-index to ...

Ways to determine if a string or HTML contains repeated consecutive elements

Assume I am working with the following string <div id="ch">abcdefg<img /><img />hij</div> <div id="ad">abc<img />defg<img />hij</div> strHtml = $('div#ch').html(); strHtmlFalse = $('div#ad&ap ...

How can I extract a specific value from an array in a JSON object by sorting it?

As someone who is relatively new to JSON and APIs, I am currently working on a project involving an API that returns values in an array structure. Here is an example of the data: { id: 0, text: "one" } { id: 1, text: "two" } ...

Having trouble getting the expected transition effects to work with Vue.js

Currently, I have a display of lists of items through the use of v-for. Initially, only the summary section of each item is visible. Upon clicking on an item, the details section is supposed to appear. This functionality is achieved by adding or removing ...

Can we adjust the starting value? Why is the Vee validate not recognizing any updates?

Within my form, I have two fields: country and region. The process involves selecting a country first, followed by choosing a region. Once a country is selected, the regions (options) are dynamically added to the next component: Region. To populate the op ...

Localhost parcel server failing to refresh

Currently, I am utilizing the parcel (v2.0.1) localhost server with hot module replacement for developing a basic web application using HTML, SASS, and JS. While the HMR functionality generally works well, there are instances where, especially after signif ...

Switching between components in vue.js: A beginner's guide

In my project, I created a Dashboard.vue page that consists of three child components: Display, sortBooksLowtoHigh, and sortBooksHightoLow. The Dashboard component also includes a select option with two choices: "Price: High to Low" and "Price: Low to High ...

How can a child value be transferred from a client component to a parent component on the server side?

I am facing a situation where a client-side component needs to send a value to its parent component which is server-side. I have tried using useState and other hooks, but so far it has been unsuccessful. Can anyone provide guidance on how to achieve this? ...

VueJS: Utilizing multiple components to respond to a single event

I am facing a situation where I have multiple components listening for the same event. Specifically, Tabs are listening for events of their content. In each Tab component, I have a bus.$on('content::event', () => {}). However, I am unsure of ...

Modify the appearance of an element within an array upon selection by comparing it with a separate array

In my code, there is an array called tagList that contains a list of objects. When one of these objects is clicked on, it gets added to another array named selectedTags. var selectedTags = []; export default class RegisterTags extends Component { con ...

Implementing a function to navigate to a different page using jQuery mobile

I'm attempting to pass a function when changing pages in jQuery Mobile, but I keep getting an error that points to `$.ajax` $( ":mobile-pagecontainer" ).pagecontainer( "change", "#schoolperformance", { reload : true, showLoadMsg : false, ...

Why is access to fetch from the origin localhost blocked by CORS policy, while posting using ajax does not face this issue?

Let's dive into the difference between AJAX and Fetch without involving CORS. I want to understand why an AJAX POST request works flawlessly while a Fetch POST request fails! Currently, I am using jQuery and AJAX for both GET and POST operations. Whe ...

Creating a JavaScript library with TypeScript and Laravel Mix in Laravel

I have a Typescript function that I've developed and would like to package it as a library. To transpile the .ts files into .js files, I am using Laravel Mix and babel ts loader. However, despite finding the file, I am unable to use the functions: ...

Binding HTML Elements to JavaScript Values

Currently, I am working on a project with .Net and Vue. However, I am facing an issue in binding a value in a label. <li v-for="restaurant in vHolidays.data" > <form id="1"> <div> ...

Utilize data from a dynamically loaded component within a parent component in Vue.js

In my Vuejs application, I've implemented a wizard-type flow with dynamically loaded components. The parent component contains the Save button, while the child components have all the text fields. Upon clicking the Save button, I need to achieve two m ...