What is the best way to display two tables side by side in a Vue component?

I am working on a vue application with a photo collection feature. My goal is to display the photos in two tables per row, iterating through the entire collection. Here's an example of what I'm aiming for:


        <row>
            <col>table1 html</col><col>table2 html</col>
            <col>table3 html</col><col>table4 html</col>
        </row>
        <row>
            <col>table5 html</col>
        </row>
    

This layout should accommodate any number of photos, always lining up two photos per row and displaying a single table in the last row if there is an odd number of photos, similar to the example above.

Answer №1

One way to access each row is by using index:

<table border=1>
  <tr v-for="row in Math.ceil(photos.length / 2)">
    <td>
      {{ photos[(row-1)*2] }}
    </td>
    <td v-if="photos[row*2]">
      {{ photos[row*2] }}
    </td>
  </tr>
</table>

Another approach is to perform array calculations directly within the template:

<table border=1>
    <tr v-for="row in Math.ceil(photos.length / 2)">
        <td v-for="photo in photos.slice((row - 1)*2, row*2)">
            {{ photo }}
        </td>
    </tr>
</table>

You could also simplify by creating a computed property:

<table border=1>
    <tr v-for="photoRow in photoRows">
        <td v-for="photo in photoRow">
            {{ photo }}
        </td>
    </tr>
</table>

Check out the demo below for implementation details:

new Vue({
  el: '#app',
  data: {
    photos: [
      'photo 1',
      'photo 2',
      'photo 3',
      'photo 4',
      'photo 5'
    ]
  },
  computed: {
    photoRows: function() {
      return this.photos.reduce((photoRows, curr) => {
        var perRow = 2;
        var prev = photoRows.pop();
        return photoRows.concat(prev.length >= perRow ? [prev, [curr]] : [prev.concat([curr])]);
      }, [[]]);
    }
  }
})
<script src="https://unpkg.com/vue"></script>
<div id="app">
  <table border=1>
    <tr v-for="row in Math.ceil(photos.length / 2)">
      <td>
        {{ photos[(row-1)*2] }}
      </td>
      <td v-if="photos[row*2]">
        {{ photos[row*2] }}
      </td>
    </tr>
  </table>
  <hr>
  <table border=1>
    <tr v-for="row in Math.ceil(photos.length / 2)">
      <td v-for="photo in photos.slice((row - 1)*2, row*2)">
        {{photo}}
      </td>
    </tr>
  </table>
  <hr>
  <table border=1>
    <tr v-for="photoRow in photoRows">
      <td v-for="photo in photoRow">
        {{photo}}
      </td>
    </tr>
  </table>
</div>

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 can I retrieve the URL of the previous page from the history object in all browsers?

Can we retrieve the URL of the previous page from the history object? I've seen references to history.previous, but it appears to be either undefined or protected based on my observations. ...

Even after configuring a proxy, the API calls are still not being redirected to the correct destination

Even after setting up a proxy, the API requests are not being directed to the correct target URL. I've built a chatbot application with create-react-app. My goal is to reroute all API calls originating from http://localhost:3000/ to http://localhost: ...

The error message states: "Cannot create element as the React object is not

Recently delving into the world of React and Material UI, I've been working on creating an AppBar with nested Tabs. Here's a snippet of my current approach: import {React, PropTypes, Component} from 'react'; import TodoTextInput from & ...

The filtering function stops working after the initial use

As I develop an app using React and Redux, my goal for the following code snippet is to function as a reducer within the main application. I have imported a filterData function, which works seamlessly the first time any Action type is selected. However, it ...

What are some solutions for resolving an infinite loop of axios requests?

I am currently in the process of developing a web app for Spotify using its API. I have encountered an issue where the handleClick function in Albums.js is being called repeatedly when trying to make a get request for specific artist album data. Could this ...

What is the best way to present retrieved JSON data from a database in Node.js without using the JSON format?

Here is the code snippet: var http=require("http"); var fs = require("fs"); var express = require("express"); var app = express(); var path = require("path"); var mysql = require('mysql'); var ejs = require("ejs") var bodyParser = require(&apos ...

How to manage multiple controllers for the same template in AngularJS?

I am facing a requirement where a single page needs to display a lot of different data, all within one vertical-scrolling page. To manage this, I have implemented collapsible divs on the page controlled by ng-if to efficiently handle the DOM elements. In ...

sum inside the while loop

Below is the provided HTML: <form> <textarea id="input1"></textarea> <textarea id="input2"></textarea> <span></span> </form> The following JavaScript code is included: $("#input2").keyup{ var a = ...

The setter of the computed property is failing to execute

Currently, I am working with a computed property that represents an object of a specific type defined within my Vuex Store. The goal is to utilize this property in my component using v-model. I have thoroughly set up getters and setters for this property a ...

The Bootstrap/Angular tab list items are generated dynamically based on the API response, leading to issues with the DOM

In one of my Angular templates, I have the following snippet. It consists of Bootstrap 3 tabs, but the tab list items (links) are generated dynamically after receiving a response from the API. <ul class="nav nav-tabs pull-right" role="tablist"> &l ...

React fails to display the content

Starting my React journey with Webpack configuration. Followed all steps meticulously. No error messages in console or browser, but the desired h1 element is not showing up. Aware that React version is 18, yet working with version 17. App.jsx import Reac ...

Vue not displaying local images

I'm having trouble creating an image gallery with Vue.js because local images are not loading. I have the src attributes set in the data attribute and can only load images from external sources. For example: data() { return { imag ...

Vue: Implementing Data Refresh in Store Post-Login

I am encountering an issue with the data store "menus" not updating after a login. It seems that the object "loggedInUser" is not set before calling "getMenus". I'm unsure of what mistake I might be making here. PS! While debugging in Chrome, I notic ...

Pressing the "Enter" key will submit the contents of

Hello, I have recently created a new chat box and everything seems to be working fine. However, I am facing an issue with submitting a message when I press enter (to go to the function Kucaj()). Can anyone provide assistance with this problem? I tried ad ...

Is there a way to locate a parent class starting from a child class, and subsequently track down another child class from the parent?

I am facing a challenge with multiple tags structured like this: <div class="A"> <div class="B1">...</div> <div class="C1">Hello World!</div> <div class="C2">World Hell ...

Angular component equipped with knowledge of event emitter output

I have a custom button component: @Component({ selector: "custom-submit-button" template: ` <button (click)="submitClick.emit()" [disabled]="isDisabled"> <ng-content></ng-content> </butto ...

Enhance the flight experience of a helicopter with jQuery game by adding smoother controls

I'm currently experimenting with creating a basic game. In this game, the user controls a helicopter and can fly it up and down. Although I have successfully implemented the basic functionality where holding the screen makes the helicopter ascend an ...

JavaScript layout: Thymealf

I have a unique thymeleaf template like so: <body> <div id="layout"> <!-- Menu toggle --> <a href="#menu" id="menuLink" class="menu-link"> <!-- Hamburger icon --> <span>& ...

I am encountering an issue with express-session where it is failing to assign an ID to

Seeking assistance with utilizing express-session to manage user sessions on arcade.ly. I have not specified a value for genid, opting to stick with the default ID generation. However, an ID is not being generated for my session. An example of the issue c ...

Navigating the website with curtain.js and anchor tags

Currently, I am working on a website located at www.TheOneCraft.co.uk. I have incorporated the curtain.js jQuery plugin to create animated slide/pages as users scroll down. However, I have been unsuccessful in making the navigation bar follow this animati ...