[Vuejs]-VueJS: How to make v-for to display 10 items per page?

2πŸ‘

βœ…

You should add another property called pageNumber initialized by 1, then use another one defined as computed property called currentPageItems based on pageNumber and perPage then loop through the currentPageItems:

props: ['perguntas'],
        data(){
            return {
                perpage: 10,
                pageNumber:0
            }
        },
      computed:{
        currentPageItems(){
          return this.perguntas.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"

2πŸ‘

You can keep an array for questions that need to be rendered and the fill the array with 5 questions whenever loadnext() method is fired which will empty old questions and fill the array with new like this.

Check this out for Live Demo

Vue Markup :

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

Vue <script> :

data: () => ({
  start: 0, // Lower limit 
  end: 5, // Upper Limit
  questions: [], // Array containing all the questions.
  toRender: [] // Array containing questions that need 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])
      }
   }
 } 

0πŸ‘

Why don’t you try to keep two arrays (primary, secondary), whenever next() method is called, you get the 10 tracked items from primary arrays and append it to the secondary array. And use v-for on the secondary array to get the all items (previous and the appended ones).

There must be better way to do that, but for time being I can only suggest you this solution.

Leave a comment