Creating an array of reusable components in Vue 3 with Typescript - How can I pass it into another component?

I have developed a customizable Button component that can be styled dynamically and accept values for text/icons, etc.

Here is the code for my "ActionButton" in Vue 3. Although I am new to this framework, I am facing some difficulties understanding certain concepts related to styling and passing props.

<template>
    <button class="pr-5 mr-3" :class="buttonStyle">
        <span class="inline-block px-2">
            <svg class="inline-block"  :class="svgStyle" xmlns="http://www.w3.org/2000/svg"  :viewBox="svgViewBox" :fill="svgFill">
                <path :d="svgValue"/>
            </svg>
            <span class="inline-block ml-4" :class="textStyle">{{ inlineText }}</span>
        </span>
    </button>
</template>
  
  <script lang="ts" >
  import { defineComponent, computed } from "@vue/runtime-core";

  export default defineComponent({
    name: "ActionButton",
    props: {
        title: {
        required: false,
        type: String,
        default: "Title",
      },
      inlineText: {
        required: false,
        type: String,
        default: "Button",
      },
      inlineTextSize: {
        required: false,
        type: String,
        default: "text-xs"
      },
      ... (continued) ...
      }
    },
  });
  </script>

I am seeking guidance on making these components reusable across multiple pages with different button configurations. Any assistance would be greatly appreciated.

I attempted to create an array of ActionButtons but struggled to correctly pass the necessary values:

<image-card
         :client-projects="clientProjects"
         image-state="true"
         :action-buttons="cardActionButtons"
        />

const cardActionButtons = ref(
    [
       {
          title: "Edit Button",
          inlineText: "EDIT",
          ... (continued) ...
      },
    ]
  )

Answer №1

If you want to incorporate dynamic content into the image-card component using slots and a v-for loop for your buttons array, here’s how you can do it:

Utilizing slots allows for the passing of content from parent to child components. In this scenario, you can have an array of buttons in the grandparent component and pass them to the image-card component through slots like this:

Parent [image-card.vue] Component

<template>
//your code for the image card component
<slot name=“button-slot”>
</template>

Grandparent component where you are utilizing image-card


..
<image-card
         :client-projects="clientProjects"
         image-state="true"
        >
 <template #button-slot>
     <div v-for=“(button,index) in    cardActionButtons” :key=“index”>
       <ActionButton :button-width=“button.buttonWidth”>
//add other props
       </ActionButton>
   </div>
 </template>
</image-card>
..

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

Ionic: Automatically empty input field upon page rendering

I have an input field on my HTML page below: <ion-input type="text" (input)="getid($event.target.value)" autofocus="true" id="get_ticket_id"></ion-input> I would like this input field to be cleared eve ...

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 ...

Executing TypeORM commands yields no output

It's been a while since I last tested my Nest project with TypeORM, and now when I try to run any TypeORM command, nothing happens. I attempted to run TypeORM using these two commands: ts-node -r tsconfig-paths/register ./node_modules/typeorm/cli.js ...

Tips for storing the device token received from Firebase Cloud Messaging in an Ionic2 application

Using the FCM plugin for ionic2, I was able to successfully implement push notifications. For reference, you can check out the plugin here. I followed the steps outlined in this Github repository, and everything is working smoothly so far. Now, my next go ...

Having trouble resolving errors in Visual Studio Code after failing to properly close a parent function? Learn how to fix this issue

Here we have the code starting with the construct function followed by the parents function public construct() //child { super.construct; } protected construct() //parent { } The issue arises where I am not receiving an er ...

How to retrieve a random element from an array within a for loop using Angular 2

I'm in the process of developing a soundboard that will play a random sound each time a button is clicked. To achieve this, I have created an array within a for loop to extract the links to mp3 files (filename), and when a user clicks the button, the ...

Exploring the Limitations of TypeScript Type Inference Using Recursive Typing

Exploring the world of Advanced Type definitions in TypeScript has been quite the challenging journey for me, as I try to experiment with different approaches. One concept I am keen on exploring is a "wizard-step-by-step" method: function fillWizardOptio ...

Tips for transferring data when clicking in Angular 5 from the parent component to the child component

I need assistance with passing data from a parent component to a child component in Angular 5. I want the child component to render as a separate page instead of within the parent's template. For example, let's say my child component is called & ...

Ways to generate an array containing the headings from a list using typescript?

How can I extract the headers of objects in an array in TypeScript? let data = [{name: "A", skills: 50, result: 80}, {name: "B", skills: 40, result: 90}, {name: "C", skills: 60, result: 60}]; let headers = Ob ...

Vue defineProps allows for the definition of complex types for properties

Within my code, I am exploring the use of complex prop types in certain instances. Below is an example of what I have in mind: enum Country { [...] } interface IPerson { firstname: string; lastname: string; } interface IAddress { street: string; ...

Setting attributes within an object by looping through its keys

I define an enum called REPORT_PARAMETERS: enum REPORT_PARAMETERS { DEFECT_CODE = 'DEFECT_CODE', ORGANIZATION = 'ORGANIZATION' } In addition, I have a Form interface and two objects - form and formMappers that utilize the REPOR ...

The error "Cannot access property afs (Angularfirestore) of undefined in the collection.set()" occurred

In the current code snippet below, I am iterating over a collection of data and updating a field if the email matches. The issue arises when trying to set new values where it crashes. The iteration process itself functions correctly, with afs being Angular ...

Experimenting with Vuejs by testing a function that delivers a Promise upon the execution of the "Created" hook

In my Vuejs application, I have the following script written in Typescript: import { Foo, FooRepository } from "./foo"; import Vue from 'vue'; import Component from 'vue-class-component'; import { Promise } from "bluebird"; @Component ...

Ways to add items to an array adjacent to items sharing a common property value

I have an array consisting of various objects const allRecords = [ { type: 'fruit', name: 'apple' }, { type: 'vegetable', name: 'celery' }, { type: 'meat', name: 'chi ...

Repeating percentages displayed in a progress bar

I created a responsive progress bar, but the progress values are repeating. I only want the central value to be displayed. Any suggestions on how to fix this issue? DEMO <div id="tab1"> <dx-data-grid class="tableTask" [dataSource]="datas" ...

Exploring the optimal method to seamlessly blend Node.js and Vue.js together

Can anyone share some recommendations on the best practices for combining Node.js and Vue.js in applications? I've been exploring different options, but I'm still unsure of the most optimal approach. ...

Need help restarting a timer I've built in Angular with just a click?

I am in the process of developing a compact application that will help me keep track of my activities within a specific time frame. Once I input an activity into a field and click "OK," it should be added to a list. My current challenge lies in resetting ...

What is the best way to ensure all keys of a certain type are mandatory, while still allowing for the possibility of

I am looking to create a mapping of key/value pairs for a specific type in the following way: required_key: string | undefined transformed to required_key: string | undefined (remains the same) required_key: string transformed to required_key: string (rem ...

Combining URL parameters into an object with NestJS's HTTP module

Is there a method for passing URL parameters to the httpService in nestjs? I want to improve the readability of this URL without resorting to Axios as nest has its own HTTPModule. Currently, this is how it looks and functions: const response = await this. ...

VSCode mistakenly detecting Sequelize findOne and findAll return type as any inferences

I have a model defined using Sequelize as shown below: import { Sequelize, Model, BuildOptions, DataTypes } from 'sequelize'; interface User extends Model { readonly id: string; email: string; name: string; password_hash: string; reado ...