Guide on implementing dynamic rowspan in tables using vue.js

I am trying to create a table similar to the one in the example photo.

https://i.sstatic.net/fkXDx.png

I attempted to connect rows using rowspan and wrote some code for it, but unfortunately, I encountered an error in the browser. To start with, here is my sample data:

    export const dummyCssTest = [
    {
        id:"1",
        name:"a",
        sub:[
            {id:"1#1",name:"b"},
            {id:"1#2",name:"c"},
        ]
    },
    {
        id:"2",
        name:"d",
        sub:[
            {id:"2#1",name:"e"},
            {id:"2#2",name:"f"},
            {id:"2#3",name:"g"},
        ]
    }
]

If the sub's id contains the same number as the main's id, e.g. "1", "2", then the names should be connected based on the number of elements in the sub array. Below is the code snippet I tried to implement. It is written in TypeScript and uses Nuxt.js and Vuetify.js frameworks. I would appreciate any advice or guidance you can provide.

    <template>
  <div>
      <v-simple-table dense>
          <thead>
              <tr>
                <th class="blue lighten-5">name</th>
                <th class="blue lighten-5">sub_name</th>
              </tr>
          </thead>
          <tbody>
              <tr v-for="item in items" :key="item.id">
                  <td :rowspan="[sub.length]">{{item.name}}</td>
                  <td>{{item.sub[sub.length].name}}</td>
              </tr>
          </tbody>
      </v-simple-table>
  </div>
</template>
<script lang="ts">
import { Component, Vue} from 'nuxt-property-decorator'
import { dummyCssTest } from "~/store/dummy";

@Component({})
export default class extends Vue{
    items:any=[]
    mounted(){
        this.items = dummyCssTest
    }
}
</script>
<style lang="scss" scoped>

</style

Answer №1

For each subitem, a row is needed rather than just for each item. This requires using 2 loops instead of 1. Additionally, there are several logical and syntax errors in your loop and in the utilization of v-simple-table.

The correct loop structure should be as follows:

<template v-for="item in items">
   <tr v-for="(subitem, iSub) in item.sub" :key="subitem.id">
      <td v-if="iSub === 0" :rowspan="item.sub.length">{{ item.name }}</td>
      <td>{{ subitem.name }}</td>
   </tr>
</template>

A separate row is generated for every subitem, with a rowspan cell created for the first subitem. A comprehensive demonstration can be found below:

const dummyCssTest = [
    {
        id:"1",
        name:"a",
        sub:[
            {id:"1#1",name:"b"},
            {id:"1#2",name:"c"},
        ]
    },
    {
        id:"2",
        name:"d",
        sub:[
            {id:"2#1",name:"e"},
            {id:"2#2",name:"f"},
            {id:"2#3",name:"g"},
        ]
    }
];
    
new Vue({
  el: '#app',
  data() {
    return {
      items: dummyCssTest
    }
  }
});
.s {
  vertical-align: top;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bccac9d9c8d5dac5fc8e928f928d89">[email protected]</a>/dist/vuetify.js"></script>
<link href="https://cdn.jsdelivr.net/npm/vuetify/dist/vuetify.min.css" rel="stylesheet">

<div id="app">
  <v-simple-table dense>
    <template v-slot:default>
      <thead>
          <tr>
            <th class="blue lighten-5">name</th>
            <th class="blue lighten-5">sub_name</th>
          </tr>
      </thead>
      <tbody>
          <template v-for="item in items">
            <tr v-for="(subitem, iSub) in item.sub" :key="subitem.id">
              <td v-if="iSub === 0" :rowspan="item.sub.length" class="s">{{ item.name }}</td>
              <td>{{ subitem.name }}</td>
            </tr>
          </template>
      </tbody>
    </template>
  </v-simple-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

The problem encountered with the Enzyme mount API is a TypeError where it is unable to read the property 'find' of an undefined variable

After converting my component to a stateless one, I started encountering an error that says: TypeError: Cannot read property 'find' of undefined Previously, my tests were running smoothly before the switch. As far as I know, you can test functio ...

After upgrading Node, the import.meta.glob feature in vite/vue3 is no longer functioning properly

Recently, I encountered an issue in my code that was previously working fine. The problem arose after upgrading from node 16 to node 20. When attempting to run 'npm run dev', I started receiving the error message: Failed to resolve import ". ...

Top method for transitioning FontAwsome stars class from regular to solid

How can I dynamically change the class of 5 stars of FontAwesome Icons from regular to solid based on a numeric variable level that ranges from 0 to 5? <template> <div id="five-stars"> <font-awesome-icon v-for="(inde ...

Creating a TypeScript type that extracts specific properties from another type by utilizing an array of keys

In my TypeScript journey, I am working on crafting a type that can transform a tuple of keys from a given type into a new type with only those specific properties. After playing around with the code snippet below, this is what I've come up with: type ...

Achieve the capability to upload multiple files in Next.js using the upload.io integration feature

I'm currently using upload.io for uploads and replicate.com for an AI model on a specific app. I am able to upload one picture, but unfortunately, I am encountering issues when trying to upload multiple pictures. Can anyone identify the problem here? ...

Using Vuejs 2 to manage assets

As a beginner in VueJS, I am exploring ways to incorporate an external JavaScript library into my component. After downloading the minified JS file and placing it in my assets directory, I'm unsure how to compile my component to utilize this library ...

In a Vue application, how can the API path be determined during the build by utilizing environment variables?

I am looking for a way to dynamically change the 'root path' of my site's API in a Vue application. I want the API path to be determined during the build process based on a variable value. This feature is available in Angular, but I'm n ...

Setting up a Lerna monorepo with TypeScript: A Comprehensive Guide

I have a central repository with the following details in config.json: "main": "dist/cjs/index.js", "module": "dist/esm/index.js", "es2015": "dist/es2015/index.js", "types": "dist/es2015/index.d.ts", "typings": "dist/es2015/index.d.ts", The repository co ...

Issue: HTMLCanvasElement.prototype.getContext is not supported in FabricJs without the canvas npm package installation

Encountered an issue while using fabric.js in my project. The error message Error: Not implemented: HTMLCanvasElement.prototype.getContext (without installing the canvas npm package) appears during project build. Seeking assistance on how to resolve this p ...

What is the best way to maintain the highlighting of a clicked navigation button in CSS?

.custom-highlight { display: inline; font-weight: 500; font-size: 15px; } .item-list { border: 1px solid #b1b8c9; color: $color-grey-light; font-size: 14px; display: inline-block; margin-right: 8px; padding: 5px 20px; border-radius: 4p ...

Typescript UniqueForProp tool not working as expected

I've created a utility function called UniqueForProp that takes an array of objects and a specified property within the object. It then generates a union type containing all possible values for that property across the array: type Get<T, K> = K ...

Completing a fetch promise and sending the outcome to a function that is not awaited

I have a function that retrieves data from a Postgresql database and returns it. The expected behavior is to fetch the data using the async function getCat(), process it in const Catalogue, and then return it to a ReactJS component. catalogue.tsx: import ...

Encountering authentication problems when using django-webpack-loader in conjunction with Vue.js, Django Rest Framework, and Rest Auth

For my project, I set up a frontend using vue.js with vue cli and webpack, and the backend using django restframework. I also added social authentication for Google using restauth. Initially, everything worked smoothly with tokenauthentication enabled in m ...

Button Component for Vue Router Link

Currently, I am in the process of developing a simple button component using Vue. My main objective is to include a prop called "link" within this component. In the parent component, my intention is to easily utilize the button component like so: <btn ...

Issue with TypeScript error encountered when attempting to save data locally using React-Redux and LocalStorage

Currently, I am delving into the worlds of React-Redux and TypeScript. Within my small app, I aim to utilize localStorage to store data locally. I attempted to address this based on information from this particular answer, but ran into a TypeScript erro ...

Tips for effectively utilizing the 'or' operator when working with disparate data types

One of my functions requires an argument that can have one of two different types. If you're interested in TypeScript functions and types, take a look at the official documentation, as well as these Stack Overflow questions: Question 1 and Question 2 ...

There is no matching overload for this call in React Native

I am working on organizing the styles for elements in order to enhance readability. Here is the code I have written: let styles={ search:{ container:{ position:"absolute", top:0, }, } } After defining the s ...

Error: Namespace declaration does not have a type annotation - TypeScript/Babel

After creating my app using the command npx create-react-app --typescript, I encountered an issue with generated code and namespaces causing Babel to throw an error. Here are the steps I took to try and resolve the issue: I ejected the project Updated b ...

What is the best ECMAScript version to select for implementing the TypeScript compiler in an Electron application?

In my Electron 5.0.6 project, I currently have es3 as the default target in my tsconfig.json file. However, I received an error message indicating that I need to upgrade to at least es6 to utilize getter/setter functionality in TypeScript. I am now contem ...

Define a module function that can be used externally

I am encountering an issue while trying to declare an external module that does not have existing typings. This library has a function that returns a string and takes no arguments. My attempt to define it in a .d.ts file is as follows: declare module "c ...