Ways to restrict the number of times elements are iterated in a `v-for`

Currently developing a compact application using Vuejs 2.0. There are around 15 elements that need to be iterated, but I would like to restrict v-for to only display 5 at a time, with additional buttons for viewing the entire list. Is it feasible to achieve this?

Answer №1

Feel free to give this code a try

<div v-if="showLess">
    <div v-for="value in array.slice(0, 5)"></div>
</div> 
<div v-else> 
    <div v-for="value in array"></div>
</div> 
<button @click="showLess = false"></button>

You will find that the new array contains only 5 elements.

Update: A minor adjustment allows this solution to work with both arrays and objects

<div v-if="showLess">
  <div v-for="(value,index) in object">
    <template v-if="index <= 5"></template>
  </div>
</div> 
<div v-else> 
  <div v-for="value in object"></div>
</div> 
<button @click="showLess = false"></button>

Answer №2

Is it too late to solve this? One way to tackle this is by utilizing computed properties:

<div v-for="value in computedObj">{{value}}</div>
<button @click="limit = null">Show more</button>

In your data section:

data(){
  return {
    object:[], // the original data
    limit: 5 // you can decide on a different number as well
  }
}

Lastly, in your computed properties:

computed:{
  computedObj(){
    return this.limit ? this.object.slice(0,this.limit) : this.object
  }
}

By clicking the button, the limit will be removed and all the data will be displayed/returned.

Answer №3

Here is a method you can test out...

<div  class="body-table  div-table" v-for="(item,index) in items"  :key="item.id" v-if="items && items.length > 0 && index <= limitationList">....

Adjust your limit in the data section

data() {
  return {
    limitationList:5
  };
},

Add a function to your button element

  <button  @click="updateLimitation(limitationList)">
    show {{limitationList == 5 ? 'more' : 'less'}}
  </button>

This is how your methods should look like

updateLimitation(limitationList){
  if (this.limitationList == this.items.length) {
    this.limitationList = 5
  }else{
    this.limitationList = this.items.length
  }
}

I hope you find this helpful...

Answer №4

This is a perfect use case for computed (I am utilizing script setup):

const paginatedList = computed(() => {
    // if dealing with arrays
    return yourArray.slice(0,5)

    // if working with objects/proxies like reactive, refs, or other computed properties
    // return yourObject.value.slice(0,5)
})

To display it in a v-for loop:

<div v-for="item in paginatedList">
    <p>{{ item }}</p>
</div

Answer №5

To solve that issue, you can calculate the limit list in the computed method.

Here is an example:

<div  class="body-table  div-table" v-for="(item,index) in filterItems"  :key="item.id">
....

<script>

export default {
  data() {
     return {
       items: [],
       limitationList:5
    };
  },
  computed: {
    filterItems () {
      return this.items && this.items.length > 0 && (this.items.length - 1) <= this.limitationList  // or any condition u want 
    }
  }
}

</script>

I hope this information is helpful.

Answer №6

Here is my unique approach: ensure that when rendering a list, you hide the main section during each iteration using the <li> tag.

 <ul role="list">
     <li v-for="(actor,index) in this.cast" :key="actor.id" :class="{'your-hidden-class': index>5}">
       <div v-if="index <= 5">
         <img v-if="actor.profile_path" :src="'https://image.tmdb.org/t/p/original' + actor.profile_path" alt="" />
         <img v-else src="/images/image-not-found.png" alt="" />
         <div>
           <div>
             <h3>{{ actor.original_name }}</h3>
             <p>{{ actor.character }}</p>
           </div>
         </div>
       </div>
     </li>
 </ul>

Answer №7

{{index}}

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div v-for="(contact, index) in allContacts" v-if="index < limitNumber" id="contacts">
  <p>{{index}}</p>
  </div>
  </div>
  <script>
        new Vue({
        el: "#app",
        data:{
      filterId:'10',
      limitNumber:10,
      allItems:[{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},],
    },
    });
    </script>

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

AngularJS : "Executing successive promises" with additional functions interspersed

Recently, I encountered a challenge in my Angular project. As a newcomer to Angular, I was tasked with modifying a directive that handles forms to ensure the submit button is disabled during processing and then enabled again once all operations are complet ...

What are the best circumstances to utilize jQuery-UI autocomplete feature?

Looking for assistance in creating an input field that auto-populates user-entered values with database entries. Only values that exist in the database should be accepted. Could someone explain the advantages of using jQuery-ui autocomplete for this task ...

Is there a way to verify if the object's ID within an array matches?

I am looking to compare the ID of an object with all IDs of the objects in an array. There is a button that allows me to add a dish to the orders array. If the dish does not already exist in the array, it gets added. However, if the dish already exists, I ...

Trouble with an external .js script

function displayMessage() { var isConfirmed = confirm("Do you want to proceed?"); if (isConfirmed) { window.location = "./proceed"; } }; function checkIfEmpty(){ console.log("checkIfEmpty"); }; @CHARSET "ISO-8859-1"; form { margin:0 auto; width:300px ...

Using the power of jQuery to load Ajax content, unfortunately, the content remains

Hey there, I'm currently working with an HTML file that utilizes AJAX to load content from other HTML files on the same server. However, for some reason, it's not functioning properly. I'm new to AJAX and I'm not sure what could be caus ...

Issue: The login.component.html file failed to load

I attempted to utilize a custom-made HTML file with the templateUrl attribute in Angular2. Below is the content of my login.component.ts file: import {Component} from '@angular/core'; @Component({ selector: 'login' , template ...

Tips for displaying diverse content in a DIV container when users click on various sections of an image

Apologies for the unclear title, but I'm struggling to explain my technical goal using jargon. The basic concept is this: there will be an image on the webpage, and when a user clicks on a specific area of the image, relevant information will appear ...

Tips for displaying information from two separate MongoDB documents on a single webpage with the help of Mongoose and Express

Currently, I am working with NodeJS, Express, EJS, and Mongoose. While I have a good grasp on most of these technologies, I find myself navigating through the complexities of Mongoose. In my project, I have established two Models that are interconnected w ...

Information is being received, but unfortunately, it cannot be displayed

Currently, I am experimenting with using the axios http request to showcase some data. My focus is on exploring how to exhibit api data on the client side with react. If you are interested in seeing my progress so far, feel free to check out the link belo ...

The user score tracking database, cataloging personal scoring history

In my database, I have a table called User. Each user in this table has a field named score. I am looking to display how the score of each user has evolved over time. My dilemma is whether to store this score separately. Should I create a new database t ...

Weaknesses found in the React Js library bundled with create-react-app

Each time I initiate a new react project using npx create-react-app <AppName>, the following vulnerabilities are detected: 96 vulnerabilities found - Packages audited: 1682 Severity: 65 Moderate | 30 High | 1 Critical Node Version: v14.18.1 Npm: 7.20 ...

Configuring JWT with Next.js and NextAuth seems to pose a challenge

Setting up JWT with NextAuth has been a bit of a challenge for me. I've been scouring GitHub posts and doing research, but haven't found much help. It seems like there's an error occurring when NextAuth tries to decode the JWT payload. All I ...

Optimal method for organizing individuals into teams using Google Apps Script

There are approximately 200 individuals in this particular department. Our goal is to form groups of 4, with each group consisting of members from different teams based in the same city. Each group must have one driver and three non-drivers, all sharing si ...

What is the best way to retrieve nested reference data all at once from a Firestore document?

I have two distinct collections stored within my Firestore database. The first collection is users, and it can be visualized as shown here: https://i.stack.imgur.com/AKlyM.png The second collection is posts, represented by the following structure: http ...

In ASP.NET, it is possible to only select a single checkbox at a time within a row in a GridView

I have a project where checkboxes are generated dynamically at runtime. I want users to be able to select only one checkbox at a time in each row. Here is my Gridview: <cc1:Grid ID="GrdWorkingCompany" runat="server" OnRowDataBound="GrdWorkingCompany_Ro ...

Testing in Jasmine: Verifying if ngModelChange triggers the function or not

While running unit tests for my Angular app, I encountered an issue with spying on a function that is called upon ngModelChange. I am testing the logic inside this function but my test fails to spy on whether it has been called or not! component.spec.js ...

Can a dynamic field name be incorporated into a JavaScript Object?

My goal is to dynamically add a field name and update the value based on that. In my situation, the eventType can have 4 types: delivery, send, open, click. However, when I implement this code, I am only getting the eventType as a string. const event = J ...

Using jQuery or JavaScript to clear multiple selections in a multiselect dropdown when a button is clicked

Is there a way to clear the dropdown selections once my function saves data to local storage? You can refer to this fiddle for more details: http://jsfiddle.net/3u7Xj/139/ I already have code in place to handle other form elements: var $form = $("#formI ...

Issue with Material UI Autocomplete: onChange event not firing

When using Material UI's Autocomplete example, I am trying to choose an option using keyboard events: Navigate through options with the Up and Down arrow keys Press ENTER to select the desired option However, the onChange event is not being triggere ...

Building web navigation using a combination of HTML, JavaScript, and PHP within a category, sub

I've been struggling to find a detailed tutorial on implementing a dynamic website navigation system using javascript or php. It seems like every time I attempt to research this topic, I end up feeling confused and unsure of where to start. My goal i ...