Inject arguments/data into the methods to showcase the name within a newly instantiated component in VueJS

I implemented a feature that allows collapsing sections within a table body. There is an "add" button represented by the "+" sign, and when clicked, it adds a new collapse section with content. I want to display the name of the data row (e.g., "iPhone") which should then appear as the title of the new collapse section.
It's functioning well, but I'm facing an issue: the title of the created collapse is displaying as "object MouseEvent".https://i.sstatic.net/SQrIq.png

CollapseSection.vue

<template>
  <div class="accordion" role="tablist">
    <b-button block v-b-toggle.accordion-1 class="collapse-btn" align-h="between">
      {{ selectText }}
      <b-icon :icon="visible ? 'caret-down' : 'caret-up'" class="icon"></b-icon>
    </b-button>
    <b-card no-body class="mb-1">
      <b-collapse id="accordion-1" v-model="visible" accordion="my-accordion" role="tabpanel">
        <SearchField></SearchField>
        <b-card-body>
          <!--     CONTENT WOULD APPEAR INSIDE THIS SLOT      -->
          <slot name="content" :addItem="addItem">

          </slot>
        </b-card-body>
      </b-collapse>
    </b-card>

    <!--  DYNAMIC CONTENT COLLAPSE WHEN CLICK ON ADD BUTTON  -->
    <div v-for="(item, index) in items" :key="index">
      <b-button block v-b-toggle="'accordion-' + (index + 2)" class="collapse-btn">
        {{ item.name }}
        <b-icon :icon="visible ? 'caret-down' : 'caret-up'" class="icon"></b-icon>
      </b-button>
      <b-card no-body class="mb-1">
        <b-collapse :id="'accordion-' + (index + 2)" accordion="my-accordion" role="tabpanel">
          <b-card-body>
            <!--     CONTENT WOULD APPEAR INSIDE THIS SLOT      -->
            <slot name="createdContent">
            </slot>
          </b-card-body>
        </b-collapse>
      </b-card>
    </div>
  </div>
</template>

<script>
import SearchField from "@/components/UI/SearchField.vue";
export default {
  name: "CollapseButton",
  components: {SearchField},
  props: {
    selectText: {
      type: String,
      default: () => "Select",
    },
  },
  data() {
    return {
      isConfiguring: false,
      configuringItem: null,
      items: [],
      visible: false,
    }
  },
  methods: {
    addItem(name) {
      const item = { name };
      this.items.push(item);
      this.isConfiguring = true;
      this.configuringItem = item;
      this.$emit('item-added', item);
    }
  },
}
</script>

DataTable.vue

<template>
<tbody>
<tr v-for="(item, itemIndex) in data" :key="itemIndex">
  <td>
      <slot></slot>
  </td>
  <td v-for="(label, labelIndex) in labels" :key="labelIndex">
    {{ item[label.field] }}
  </td>
</tr>
</tbody
</template>
<script>
export default {
  name: "DataTable",
  components: {ActionColumn},
  props: {
    labels: {
      type: Array,
      required: true,
    },
    data: {
      type: Array,
      required: true,
    },
  },
  methods: {
    addItem(name) {
      this.$emit('add-item', name);
    }
  }
}
</script>

NewLab.vue

<CollapseSection select-text="Select Images">
    <template #content="{ addItem }">
      <DataTable :labels="labels" :data="data" :showAdd="true">
        <b-icon icon="plus" class="add-btn" @click="addItem(data.name)">
        </b-icon>
      </DataTable>
    </template>
    <template #createdContent>
      <CollapseTabContent>

      </CollapseTabContent>
    </template>
</CollapseSection>
<script>
const labels = [
  {text: "Name", field: 'name'},
  {text: "Description", field: 'description'},
]
const data = [
  {name: 'Windows 1', description: 'Password Cracking'},
  {name: 'Windows 13', description: 'SIEM and MISP machine'},
  {name: 'Windows 15', description: 'AD auditing lab'},
  {name: 'Windows 31', description: 'Threat Hunting and Investigation'},
];

export default {
  name: "NewLab",
  components: {DataTable, CollapseSection},
  data() {
    return {
      labels: labels,
      data: data,
    };
  },
</script>

Answer №1

SOLVED. I exhausted all possible solutions without success. Seeking help from GPT, various QNA forums, and VueJS community on Telegram yielded no results. I refrained from using other technologies like VueX, opting instead to focus on isolating the Dynamic content of Collapse into a separate component called DynamicCollapse.vue

  <template>
  <!--  DYNAMIC CONTENT COLLAPSE WHEN CLICK ON ADD BUTTON  -->
  <div>
    ...
  </div>
</template>

<script>
export default {
  name: "DynamicCollapse",
  items: [],
  props: {
    dynamicCollapses: {
      type: Array,
      default: () => []
    },
  },
  data() {
    return {
      isVisible: [],
    };
  },
}
</script>

In addition, I made the decision not to pass the add button as a slot into DataTable

<!-- A dynamic column for add button -->
    ...
</code></pre>
<p>The method in DataTable.vue is as follows:</p>
<pre><code>methods: {
addItemToDynamicCollapse(name) {
  this.$emit("add-to-dynamic-collapse", name);
},

Lastly, in the parent component:

...

In the parent component's section, I passed the data and method(I will refactor it in the future)

data() {
    return {
      dynamicCollapses: [],
    };
  },
  methods: {
    addDynamicCollapse(name) {
      this.dynamicCollapses.push({
        name: name,
        content: {} // Add your content here
      });
    }
  },

I invested a week in solving this issue through extensive reading and research on slots, data, scoped slots, etc. I believe this solution will be beneficial to you.

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 ".splice()" method continuously removes the final element from an array

I have implemented a function on my form that allows me to add multiple file inputs for various images by clicking a button. Although this functionality is working correctly, I am facing an issue while trying to delete an input field using .splice. Instead ...

Refine Your Search Findings

I have a code snippet that enables searching items from a dropdown menu with a search bar, but now I want to remove the dropdown and only keep the search functionality. How can I modify the code to separate the select feature from the independent search ...

Converting JSON data into XML format

When I am converting JSON Values to XML, instead of getting JSON properties as elements of XML, I am receiving "title":"source". The desired output should be <title>source</title>. Can you help me identify what mistake I mig ...

What is the best way to utilize external module imports for SVG React components in a create-react-app project?

Understanding the Project Structure To ensure code reusability across multiple React projects, a specific project structure has been established: @foo/design: Includes design elements like raw SVG images @foo/ui: A React library based on Create React App ...

What is the method for inserting form control values into a QueryString within HTML code?

Struggling with passing HTML form control values into a QueryString for page redirection. While I can easily input static values into a QueryString and retrieve them using PHP's GET method, I am encountering difficulties when it comes to dynamic valu ...

Utilizing a CSS identifier with jQuery

I'm struggling with a basic .each statement for comments where I want a form at the bottom to add new comments. The goal is simple - when someone submits a comment, I want it to display just above and move the form down using jQuery. Although this fun ...

What are the steps to executing commands with child processes in Node.js?

I have successfully established communication between the client and server using socket.io. I am now utilizing WebSockets to send commands from the client to the server, and I would like to execute these received commands on the server. Here is my approa ...

techniques for presenting tabular data in a JavaScript modal

Hey there! I'm looking for a way to show table formatted data in a JavaScript popup. Do you know if it's possible to display table formatted data in a JavaScript popup using ASP.NET and C#? ...

Ways to ensure the first div always expands when sorting in AngularJS

In my AngularJS application, I have a set of div elements generated using ng-repeat. The first div is always expanded by default upon loading the page. Now, when I click a button to sort the divs based on their ID in the JSON data, I want the top div to ...

Tips for incorporating external routes into the routes index file

I am currently dealing with a users.js and an index.js file. users.js const express = require('express'); const router = express.Router(); const {catchErrors} = require('../handlers/errorHandlers'); const authController = require(&ap ...

Running JavaScript Code Inside a Custom User Component

I am currently working on developing an ASP.NET user control that has the ability to load a specific RSS feed by providing its URL. My goal is to encapsulate all the functionality within the user control so that it can be easily inserted into any page, set ...

Instructions for sending an array of integers as an argument from JavaScript to Python

I have a JavaScript function that extracts the values of multiple checkboxes and stores them in an array: var selectedValues = $('.item:checked').map(function(){return parseInt($(this).attr('name'));}).get(); My goal is to pass this a ...

JavaScript Flash player for iPad

As many of us know, the iPad does not support Flash. However, I am curious if the iPad sends any specific error messages that can be captured using Javascript. I realize one method is to detect the iPad from the user agent string, but I am interested in w ...

Vows, Tobi, and Node.js come together for comprehensive REST API testing

Currently, I am in the process of merging the examples here and here to create a vows test for my node.js / express application that does the following: Creates a new user object Verifies that the response is correct Utilizes the returned _id to perform ...

Tips for effectively utilizing a javascript constructor in typescript

I am attempting to incorporate a Javascript library into my Typescript project. Within the JS library, there is a class called pdfjs-dist with a constructor that is used in this manner: findController = new _pdf_find_controller.PDFFindController({ li ...

What is the best way to connect to the Microsoft Azure Machine Learning Studio API - through Vue Axios or an Express

I am currently utilizing the following code to establish a connection with a web service. However, I now require assistance in connecting to the Microsoft Azure Machine Learning Studio Api using Vue Axios or Express. Can someone provide guidance? var http ...

Personalized function callback for jQuery extension

Looking to integrate this particular example into my project. I do not have much expertise with jQuery and have not worked extensively with JavaScript objects in the past. What I would like to achieve is a simple modification on this plugin so that it tri ...

Struggling to display the preloader animation while waiting for the render.com server to start up (using the free tier web service)

My choice for deploying dynamic websites is render.com and I am currently using their free tier. The issue with this free service is that Render spins down the web service after 15 minutes of inactivity, resulting in a delay when it needs to spin back up u ...

Utilizing Axios to Fetch Data from an External API in a Next.js Application

I'm looking to retrieve data from an API and display it on a webpage. My application has API routes set up. Within api/apps/get-apps.js: import { APPS_PATH, BASE_URL } from '../constants/api.constants'; import axios from 'axios'; ...

Tips for seamlessly integrating an overlay into a different image

My current system is set up to overlay the image when you check the checkboxes. However, I'm facing an issue with positioning the image inside the computer screen so it's not right at the edge. Can anyone provide assistance with this? <html&g ...