Tips for iterating within a Vue.js template without disrupting the HTML structure

Currently, I am attempting to implement a loop within a table. However, I have encountered an issue with the following code:

<tr v-for="( block , index ) in listRenderBlock" :key="index">
    <div v-for="( section , i ) in block.sections" :key=" i ">
        <td> 
           <p>
              {{ block.name }}
           </p>
        </td>
        <td>
           <p>
              {{ section.name }}
           </p>
        </td>
    </div>
</tr>

When attempting this type of looping structure, the div element disrupts the integrity of the table's layout. I understand that in React, one can use something like:

blocks.sections.map(value => ....)

However, it appears that this approach does not work as expected in Vue.js either. I would greatly appreciate any suggestions or feedback on how to address this issue. Thank you for taking the time to read through this query.

Answer №1

For looping without using wrappers, consider utilizing a <template>:

<tr v-for="( block , index ) in listRenderBlock" :key="index">
  <template v-for="(section , i ) in block.sections">
    <td :key="`b_${index}_${i}`"> 
      <p>
        {{ block.name }}
      </p>
    </td>
    <td :key="`s_${index}_${i}`">
      <p>
        {{ section.name }}
      </p>
    </td>
  </template>
</tr>

Note: It's important to remember that <div>'s are not valid children of <tr>.

To see this approach in action:

Vue.config.productionTip = false;
Vue.config.devtools = false;

new Vue({
  el: '#app',
  data: () => ({
    listRenderBlock: [{
      name: 'B-1',
      sections: [
        { name: 'S-1' },
        { name: 'S-2' }
      ]
    }, {
      name: 'B-2',
      sections: [
        { name: 'S-1' },
        { name: 'S-2' }
      ]
    }]
  })
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<table id="app">
  <tr v-for="(block, index) in listRenderBlock" :key="index">
    <template v-for="(section, i) in block.sections">
      <td :key="`b_${index}_${i}`"> 
         <p v-text="block.name" />
      </td>
      <td :key="`s_${index}_${i}`">
         <p v-text="section.name" />
      </td>
    </template>
  </tr>
</table>

Additionally, keep in mind that <template> elements cannot be given a :key, as they do not directly translate to DOM elements. Therefore, you'll need to create your own unique keying system for the actual DOM elements. In this case, we used keys based on a combination of index and i, with prefixes indicating whether it's for a block or section element. The format of the keys doesn't matter, as long as they are distinct. (These keys are only utilized by Vue internally to update DOM elements when your data changes).

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

A guide on choosing a custom button color and automatically reverting to its original color when another button is clicked

I have a collection of 24 buttons, all in a dark grey (#333333) shade. Whenever I click on one of the buttons, it changes to a vibrant blue color (#0099ff), which is functioning correctly. However, when I proceed to click on another button, the previous ...

The hover effect does not carry over to duplicated HTML

I successfully added a node, but I forgot to include the hover function of the node in my application. The hover function is not necessary, and I need it to work with ie8 compatibility. Here's my HTML: <div id="appendCell" style="color:green; colo ...

Placing a MongoDB query results in an increase of roughly 120MB in the total JS heap size

I'm puzzled by the fact that the heap size increases when I include a MongoDB database query in a function within my controller. Here is the code for my router: import { Router } from "express"; import profileController from '../contro ...

Is it possible to utilize various return values generated by a regex?

Working on a project where I am utilizing regex to extract links from a Google Calendar XML feed. The links appear in the following format: <a href="http://www.drsketchysdublin.com/event-registration/?ee=11">http://www.drsketchysdublin.com/event-reg ...

The error in React syntax doesn't appear to be visible in CodePen

Currently, I am diving into the React Tutorial for creating a tic-tac-toe game. If you'd like to take a look at my code on Codepen, feel free to click here. Upon reviewing my code, I noticed a bug at line 21 where there is a missing comma after ' ...

"Utilize Meteor to transmit emails to internal email addresses within the intran

I have successfully developed a Meteor App to manage requests. However, I am facing an issue where I need emails with default text to be sent whenever a request is created or updated. The challenge lies in the fact that I am operating within an intranet e ...

Choose an item from a list that does not have a particular class

Here is a list of items: <ul id='myList'> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> <li class='item-selected'>Item 4</li> <li>Item 5</li> & ...

Is there a way to verify that all CSS files have been successfully downloaded before injecting HTML with JavaScript?

I am looking to dynamically inject HTML content and CSS URLs using JavaScript. I have more than 3 CSS files that need to be downloaded before the content can be displayed on the page. Is there a way to check if the aforementioned CSS files have finished ...

What is the best way to iterate through two arrays without disrupting the sequence of displayed elements?

I am currently working on developing a chat-bot that includes the functionality of sending and receiving voice audio. To achieve this, I have implemented two separate array states: one for rendering text messages and another for rendering audio messages. I ...

The new mui v5 Dialog is having trouble accepting custom styled widths

I am facing an issue with my MUI v5 dialog where I cannot seem to set its width using the style() component. import { Dialog, DialogContent, DialogTitle, Paper, Typography, } from "@mui/material"; import { Close } from "@mui/icons- ...

Knockout JS: Choosing specific dropdown elements

My array doorsForSite contains a list of doors, each with its own set of schedules. Here is how it looks: var scheduleList = new[] { new { ScheduleId = "Schedule1",ScheduleName = "Always On" }, new ...

Is there a way to verify if an array has been initialized and holds a value simultaneously?

Is there a more concise and elegant way to check if ['pk'] exists in the first item of an array before executing certain tasks? The array may not always have data, leading to bloated code. I'm looking for a streamlined solution in Javascrip ...

The button will continue to be enabled even if the textfield is empty

I have a task to implement a feature on a webpage where the submit button should remain disabled until all values are entered in the textbox. However, I am facing an issue where the submit button is already active when the page loads. .directive('pas ...

Function that yields promise result

I need help figuring out how to make this recursive function return a promise value. I've attempted various approaches, but they all resulted in the search variable ending up as undefined. public search(message: Message) { let searchResult: strin ...

Display icon within ng-bind-html when the value is not true

Is there a way to integrate a fontawesome icon into ng-bind-html on ui-select based on a boolean value? <span ng-bind-html="project.IsActive == false && <i class="fa fa-ban" aria-hidden="true"></i> | highlight: $select.search">& ...

Display the hidden div element when clicked

In my code, I have two div elements as follows: <div class='staticMap'></div> <div class='geolocation-common-map'></div> Initially, the 'geolocation-common-map' div is removed using jQuery when the pa ...

What steps do I need to take in order to establish a connection to a GridFS bucket

I have successfully implemented file uploads using a gridfs bucket. However, I am facing challenges with downloading files. For retrieving files, I need to access the bucket instance that I created within the database connection function: const connectDB ...

Using an Angular route to trigger the resolution of data from a service

I'm having trouble figuring out how to implement Angular route resolve. The documentation does not provide much help for more complex aspects of the javascript framework like this. Here is the service I am using: app.service("AuthService", ["$http", ...

Algorithm to identify the highest sum of two numbers in a disorganized array of whole numbers

I am looking to create a function that can identify the largest pair sum in an unordered sequence of numbers. largestPairSum([10, 14, 2, 23, 19]) --> 42 (sum of 23 and 19) largestPairSum([99, 2, 2, 23, 19]) --> 122 (sum of 99 and 23) largestPairSum ...

What is the reason for `this` becoming undefined within the filter() function in VueJS?

Currently, I am in the process of designing a Date of Birth (DOB) Form. The interesting part is that I have incorporated VueJS into the form to enhance user experience. The unique feature of this form is that users are required to input their month of bir ...