Using two variables for iteration in Vue.js v-for loop

Can you create a v-for loop with two variables?

I attempted the following, but it did not function as expected

<ul id="example-1">
  <li v-for="apple in apples" v-for="banana in bananas">
    {{ apple .message }}
    {{ banana .message }}
  </li>
</ul>

Your assistance is greatly valued!

Answer №1

A good approach would be to create a computed property that merges the two arrays into an array of objects.

By doing this, you can effectively handle scenarios where the arrays have different lengths. For instance:

computed: {
  fruit() {
    const fruit = []
    for (let i = 0, len = Math.max(this.apples.length, this.bananas.length); i < len; i++) {
      fruit.push({
        appleMessage: this.apples[i] && this.apples[i].message || 'no apple message',
        bananaMessage: this.bananas[i] && this.bananas[i].message || 'no banana message'
      })
    }
    return fruit
  }
}

You can then iterate through the merged array like so:

<li v-for="f in fruit">
  {{ f.appleMessage }}
  {{ f.bananaMessage }}
</li>

Check out the demo here: http://jsfiddle.net/wzmL1y6q/

Answer №2

How about trying this approach?

<div id="container">
  <ul v-for="(item, index) in items">
   <li> {{ item.name }} {{ fruits[index].name}} </li>
  </ul>
</div>

Just remember to confirm that both arrays are of equal length.

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

How to target and set focus on dynamically generated input field when the ID is unknown

I am facing an issue with a jQuery/AJAX function that loads HTML form elements from the server. The form fields vary, and I want to set focus on the first available input field after the load is complete. I have tried: $(':input:enabled:visible:firs ...

Having trouble getting the vue-slick-carousel to function properly when using it from the CDN

Struggling to implement a small app using the CDN script at , but so far no success. I'm a novice with vue.js and unsure if I need to import anything. According to the documentation, importing is required: Vue-slick-carousel Following this structure ...

What is the most effective way to save numerical information to a file?

Imagine a scenario where there is an array filled with one million random numbers: [ 0.17309080497872764, 0.7861753816498267, ...] The task at hand is to store these numbers onto a disk for future retrieval. While storing them in text formats like JSON or ...

The Chrome extension functions properly when the page is refreshed or loaded, but it does not work with internal navigation

When landing on a YouTube page starting with w*, I have a script that triggers an alert with the URL. However, this only works when entering the page directly or upon refreshing. I am trying to make the alert trigger when navigating internally to that page ...

What is the process for incorporating a full-page blog into a blog preview?

I customized a template, but there is a blog section within the div that I am struggling to replicate. Here is the test website for reference: Below is the HTML code for the blog section: <!-- Blog Start --> <section class="section bg ...

UI is experiencing lag issues post Alert invocation in React Native

// When a text field is pressed, an alert function is called. This function opens an alert and then calls another function on confirmation. However, the application gets stuck when "showAlert1()" is called, and this function is being invoked multiple times ...

Enable automatic full-screen mode on Google Chrome upon page load

I would greatly appreciate it if you could provide an answer to this question, even if it is marked as a duplicate. I have tried various solutions and sought help, but unfortunately, nothing seems to be working for me... What I really need is for the brow ...

Catch the return of the transition event

My website is built on asp net core, with all pages displayed as partialviews to create a spa model without relying on angular or other frameworks. By switching partialviews, I can easily modify the page's url using window.history.pushState ("objec ...

The tweet button is not displaying correctly on the website

Visit my website here, where I have integrated a tweet button generated from Twitter.com. It was working fine for the initial few posts, but now it is failing to load and only displaying text. I have checked the console for any JavaScript errors, but so f ...

Are there any tools available that can convert ThreeJS code into WebGL?

Are there any existing tools that can convert ThreeJS to WebGL? Or, could you provide guidance on creating a converter for ThreeJS to WebGL? ...

Vue email validation is failing to return a valid email address

I'm relatively new to Vue and have implemented email validation using the reg expression in my Vue script data for this project. By utilizing console.log(this.reg.test(this.email)) and observing the output while users input their email, the validation ...

Localhost is unable to process AngularJS routes containing a dot in the URL

When using the route provider and setting this specific route: .when('/:name/:id', { It successfully navigates to my desired path and executes the code when I enter: https://localhost.myapp.com:9000/Paul/123 However, it fails to work with this ...

Issue with Jquery event not triggering correctly following ajax data retrieval

This script uses jQuery and Ajax to populate a navigation bar with categories and subcategories dynamically. The first unordered list is static, while the second one is populated after receiving data via Ajax. There are some jQuery events that need to be i ...

Error encountered while trying to display the react-bootstrap table

I am having trouble rendering sample data using react-bootstrap tables. Every time I try, I encounter the error: TypeError: Cannot read property 'filter' of undefined I've searched on various platforms and visited multiple links, but I ca ...

The previous button on Owl Carousel seems to be malfunctioning after navigating from a different page

In my case, I have two distinct pages: let's call them the first and second pages. On the first page, I utilize an owl carousel slider with a tag that links to a specific slide on the second page's owl carousel slider using an ID. Meanwhile, on ...

Issue with dropdown component in material ui version v1.0 beta 26 encountered

Currently, I am encountering an issue with the dropdown component while using Material UI v1.0 beta.26. In this updated version, you are required to utilize the Select component along with MenuItem. Although my dropdown is successfully populated upon rend ...

Stop Browsers from Saving the Current Page in the History Log

Currently, I am facing an issue with a user-triggered popup window on my website that redirects to another site. It is important that users do not access this page directly and only navigate to it if the popup window opens as intended. mysite.com -> my ...

Objects remaining static

I'm currently working on a VueJS component that has the ability to export data into .xlsx format. To achieve this functionality, I am utilizing the json2xls library, which requires an array of objects with identical keys (representing column names) to ...

Can someone please explain how to include a custom icon on Select component in Mantine without using an image from Tabler Icons library?

Hey there, I'm new to using Mantine and I'm currently working on a Search Component. Instead of utilizing an image from the tabler icons like in the Mantine examples, my goal is to include a picture from my own assets. Here's what I've ...

Incorporating a node module into my Angularjs application

Recently, I stumbled upon a handful of modules that I would like to incorporate into my Angular app. However, I find myself at a crossroads on how to effectively integrate them into my project as I will need to use "require()" in my factory file. One part ...