What is the best way to nest a v-for inside another v-for in Vue.js?

BaseAccordion.vue

<template>
  <div class="wrapper">
    <div class="accordion">
      <input type="checkbox" @click="toggleItem" />
      <h2 class="title">
        <slot name="title"></slot>
      </h2>
    </div>
    <div v-show="show" class="content">
      <slot name="content"></slot>
    </div>
  </div>
</template>
<script>
export default {
  components: {},
  data: function () {
    return {
      show: false,
    };
  },
  methods: {
    toggleItem: function () {
      this.show = !this.show;
    },
  },
};
</script>
<style scoped>
.wrapper {
  margin: 0 auto;
  width: 300px;
  padding: 10px;
}
.accordion {
  display: flex;
  cursor: pointer;

  margin: 0;
}
.title {
  margin: 0;
  color: darkgreen;
}
.content {
  text-align: left;
  width: 100%;
  border-bottom: 1px solid black;
  padding: 10px;
}
</style>

Issue detected in the code above is that,

When attempting to loop through a list inside another list (using nested v-for loops),

I am encountering each value being repeated multiple times, leading to duplicated sub items due to repetitive item display.

Answer №1

To meet the requirement, it is important to execute the second for loop only within the context of v-slot:content

HelloWorld.vue

Template

<div v-for="box in boxes" :key="box.id">
  <BaseAccordian>
    <template v-slot:title>{{ box.name }}</template>
    <template v-slot:content>
      <div
        v-for="paint in paints"
        :key="paint.id"
        class="line"
        :class="{
          green: paint.status === 'ok',
          red: paint.status === 'notok',
          pink: paint.status === 'medium',
        }"
      >
        <div>{{ paint.name }}</div>
      </div>
    </template>
  </BaseAccordian>
</div>

CSS

.content > .line > div {
  --line-width: 2px;
  --x-offset: 8px;
  --x-width: 120px;

  position: relative;
  padding-bottom: var(--line-width);
}
.content > .line > div:before {
  content: "";
  display: block;
  position: absolute;
  bottom: 0;
  left: var(--x-offset);
  width: var(--x-width);
  height: 100%;
  border-left: var(--line-width) dashed currentColor;
  border-bottom: var(--line-width) dashed currentColor;
}
.content > .line > div:after {
  content: "";
  display: block;
  position: absolute;
  bottom: calc(-1 * var(--line-width) * 1.75);
  left: calc(var(--x-offset) + var(--x-width));
  width: 0;
  height: 0;
  border: calc(var(--line-width) * 2.5) solid transparent;
  border-right: 0;
  border-left: calc(var(--line-width) * 5) solid currentColor;
}

Working Code

Fiddle

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

When positioned at high or low angles, the camera starts acting strangely

In my Three.js scene, I have a camera that I need to move and change its angle around a specific focal point. The focal point is actually the camera's position, and during rendering, I translate the camera by using the cameraBuff vector to position it ...

What is the best way to access data from a static config.json file in TypeScript within a Vue component following the execution of a build:electron command in Vue CLI 3?

Hey there! I've been considering whether it's feasible to include a config.json file in a Vue CLI 3 project that can be dynamically read at runtime, both during development and production stages. This config.json file will hold key strings that ...

Running a Mongoimport command within a JavaScript/Node.js script

Is there a node.js/javascript library available that allows for the use of mongoimport within code? From what I understand, mongoimport is similar to an .exe file that needs to be executed before being able to utilize its text input environment. Is it fe ...

Problem identified with Vue.js: The Log in screen briefly flashes before redirecting the authenticated user (resulting in a full page refresh)

My routing is functioning properly, utilizing navigation guards to prevent users from accessing the login or register routes once they are signed in. However, when I manually type '/auth/signin' in the address bar, the login screen briefly appear ...

Protecting API EndPoints using JSON Web Token (JWT)

Help Needed: Issue with JWT Authorization I'm currently working on a project that involves CakePHP Backend and Vue Frontend. I am in the process of securing my API Backend using JWT Security. I have implemented the 'ADmad/JwtAuth.Jwt' Plugi ...

Encountering a JSON_PARSER_ERROR when trying to call Google FCM using MobileFirstAdapter JS

I am working on integrating Google FCM Api for sending Push Notifications. Below is the snippet of code from my JavaScript file: function sendNotificationToUser() { var request={ path :'/fcm/send', method: 'POST&ap ...

Having trouble using angular.isString in conjunction with ng-repeat

Is there a way to use angular.isString for comparison within an ng-if in an ng-repeat loop? Currently, all items in the array are being returned. I attempted to simply display the result of angular.isString, but no output is generated. This is my desired ...

Tips for eliminating blank rows from _POST following a PHP and JQuery post

My AJAX jQuery post is working fine, but the result looks like this: Array ( [facdatas] => Array ( [0] => Array ( [mbr_id] => 26 ) [1] => Array ( ...

The task of mapping an array of objects with nested values using JavaScript is proving to

Attempting to convert an array of objects with nested values in child objects like: const objs = [{ "B": { "value": 1, }, "D": { "value": "45" }, "E": { "value": "234" }, ...

Possible Inconsistencies with the LookAt Feature in Three.js

Attempting to use the lookAt function to make zombies move towards the character has been a challenge. The problem lies in the fact that they are not turning correctly but at odd angles. Here is the code snippet I tried: var pos = new THREE.Vector3(self ...

Access the contents of objects during the creation process

I am currently in the process of creating a large object that includes API path variables. The challenge I am facing is the need to frequently modify these API paths for application migration purposes. To address this, I had the idea of consolidating base ...

The NonErrorEmittedError message indicates that component lists rendered using v-for must include explicit keys

Upon executing the command gulp --ship, an error message appears in the terminal: NonErrorEmittedError: (Emitted value instead of an instance of Error) <app-Player-List v-for="player in players">: component lists rendered with v-for should have ...

Using three.js to control the opacity and size of points

I have returned with question number two about points. My query this time revolves around changing the opacity from 0 to 1 and back within specific pixel distances from the emitter. var particleCount = 14, particles = new THREE.Geometry(), pMaterial = new ...

Covering Vue methods with Jest and Coverage: a comprehensive guide

My goal was to improve the code coverage percentage by covering specific if statements within Vue methods. I am using package versions @vue/test-utils:"^1.1.4" and vue: "^2.6.12". Below is a snippet of my component: <template> <div :class=& ...

Delegate All Events to the Document

In my current setup, I have over 350 events that look like: $(document).on('click','.removable-init',function(){}); I've noticed a performance issue where some click events are delayed by a fraction of a second. This is happening ...

Changing the input value in Nuxt / Vue 2 after it has been overridden

I'm working on a feature where the user's typed keys are converted to the last single upper-cased character (for example, 'a' becomes 'A', 'abc' becomes 'C'). Here is my current code snippet: <template& ...

What could be causing my overloaded controller methods to not be receiving requests correctly?

Within my view, I have a page called PrintPatientConsent.aspx that I need to call for two different types. However, only the default action method is being called by default, even when passing parameters. Here is the code snippet for reference: [Accept ...

Drop delete method not functioning as expected

Currently, I am trying to work on a JavaScript delete function that is supposed to delete a row from an SQL table. However, it seems like the function is not working properly. Let me share the code with you: $(document).ready(function(){ $( "#draggabl ...

Make sure to search for the CSS class in the Twig file that is compatible with Vue.js and functions

I am currently working on a twig file for a Drupal 8 project and I am still trying to familiarize myself with it. In the past, I had a Vue file where I included the following code snippet: <div class="dropdown-menu":aria-labelledby="menu ...

Fill a popup window with data retrieved from a MySQL query result

I have created an HTML page that displays data retrieved from a MySQL database. Users have the option to edit records, and I want to implement a modal form that opens up and shows data related to a specific "id" from the database when the edit button is cl ...