Using v-for to pass two properties to a single component in VueJS

Hey there!

I'm trying to create a v-for loop with a component that has two different props

COMPONENT

<template>
    <div class="bg-light rounded p-2 px-5">
        <h5> {{ number }}</h5>
        <h3>{{ item }}</h3>
    </div>
</template>
  
<script>
export default {
    name: 'CustomCard',
    props: ['item', 'number']
}
</script>

V-FOR INSIDE ANOTHER COMPONENT

<template>
     <div class="row m-auto">
            <CustomCard 
                v-for="(card, index) in cards" 
                :key="index"
                :item="card.item"
                :number="card.number"
                class="col m-3"/>
      </div>
</template>
<script>
import CustomCard from './CustomCard.vue';
export default {
    name: 'DashboardSection',
    components: {
        CustomCard
    },
    data () {
        return {
            cards: [
                { item: 'Impressions', number: '2.300' }, 
                { item: 'Clicks', number: '259' },
                { item: 'Conversions', number: '45' },
                { item: 'Cost', number: 'R$ 350,00' }
            ]
        }
    }
}
</script>

Can anyone help me figure out how to include the card number using v-for as well? The current setup works but I want to utilize both props, not just the item

Answer №1

If I understood correctly, make sure to retrieve the correct number with its index:

Vue.component('highlightCard', {
  template: `
    <div class="bg-light rounded p-2 px-5">
        <h5> {{ cardNumber }}</h5>
        <h3>{{ cardItem }}</h3>
    </div>
  `,
   props: ['cardItem', 'cardNumber']
})
new Vue({
  el: "#demo",
  data () {
    return {
      cardItems: ['Impressões', 'Cliques', 'Conversões', 'Custo'],
      cardNumbers: ['2.300', '259', '45', 'R$ 350,00']
    }
  },
  methods: {
    num(val) {
      return this.cardNumbers[this.cardItems.findIndex(i => i === val)]
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
  <div class="row m-auto">
    <highlight-card 
        v-for="(itemCard, index) in cardItems" 
        :key="index"
        :card-item="itemCard"
        :card-number="num(itemCard)"
        class="col m-3"/>
  </div>
</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

A guide on enhancing Autocomplete Tag-it plugin with custom tags

Looking to expand the tags in the 'sampleTags' variable within this code snippet $(function () { var sampleTags = ['c++', 'java', 'php', 'coldfusion', 'javascript', 'asp', &apo ...

Explore the feature of toggling visibility of components in Vue.js 3

I am facing an issue with showing/hiding my sidebar using a button in the navbar component. I have a navbar and a side bar as two separate components. Unfortunately, none of the methods I tried such as v-show, v-if, or using a localStorage value seem to wo ...

Guide on creating an alias in webpack within vue-cli4?

Is there an alternative method for setting the alias in vue-cli4 since there is no webpack.base.conf.js file? Thank you! ...

Utilizing database information to dynamically select Nightwatch.js tests for execution

Currently, I am in the process of configuring nightwatch tests for a specific website. The setup involves assigning testing personas to run tests, which works smoothly in our development environment. However, we face an issue when we need to dynamically ad ...

What is the best way to create a smooth transition for a bootstrap navbar in chrome, toggling from right to left on

I have successfully modified the bootstrap navbar to toggle from right to left instead of top to bottom using the following code: For HTML- <nav class="navbar navbar-inverse" role="navigation" style="height: 55px; padding-top: 2px; background-color: # ...

Vuetify's v-bottom-navigation appears to have been shifted downwards

This is the main route page in my application <template> <div> <MobileMain v-if="$vuetify.breakpoint.xsOnly"/> <Navigation v-else/> <router-view></router-view> </div> </template> &l ...

When you try to import a component, it may result in a blank page displaying an error message stating: "TypeError: Cannot set property 'components'

One interesting feature is the Vue component named DisplayContent, <template> <div></div> </template> <script lang="ts"> import { Vue, Component } from "vue-property-decorator"; import Home from "@/ ...

The scrollTop feature fails to function properly following an Axios response

I'm currently facing a challenge with creating a real-time chat feature using Laravel, Vue.js, Pusher, and Echo. The issue arises while implementing the following 3 methods: created() { this.fetchMessages(); this.group = $('#group') ...

Is there a way to add a stylesheet file to just one specific template?

I am facing an issue with including a Materialize.min.css link. Here is the code I have: <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css"> However, I only want to incl ...

Change the class of multiple elements using jQuery with a set time interval

Here is a clever jQuery snippet I've put together to toggle the class of an element at intervals: setInterval(function(){$('.grid-item .slide-image').toggleClass('active')}, 800); The code runs smoothly! However, I now have multi ...

What is the best way to create navbar items using vue-router links that will toggle the visibility of the navbar?

I have a navigation bar that is functioning properly, except for the fact that it does not close when an item is clicked. It only closes when I click anywhere else in the window. My setup involves Laravel 8 and Vue 3 with Bootstrap 5 installed. This is m ...

Tips for positioning HTML elements at the exact mouse location as it moves, without any delay?

Currently, I am in the process of developing a web-based drawing application that does not rely on using a canvas. My decision to avoid using a canvas is because I plan to incorporate CSS Keyframes into the HTML elements upon placement. This approach allow ...

What is the best way to implement vuelidate when dealing with an array of objects?

In my form questionnaire, I am looping through an array of objects. Each object has five properties, but only one property needs validation. The validation setup in the component looks like this: specificGifts: { $each: { passThrough: { ...

"Effortlessly Engage Users with Rails and AJAX Comment Posting

Running a simple blog app dedicated to video game reviews, I encountered an issue with AJAX. As a self-taught student developer, I'm facing a challenge where posting comments on review pages triggers a full page refresh instead of dynamically updating ...

Encountering a 404 error in Angular MVC project while trying to load a

Trying to access an edit partial named AddEditPersonModal.cshtml from a different folder in my MVC project, in order to load its contents into a UI Bootstrap modal using Angular. However, when the index.cshtml page loads, I encounter a 404 error related to ...

Leverage the power of Vue.js with the babel plugin-proposal-class-properties

In one of my classes, I make use of some static properties like this: class Entity { static LIMIT = 10; } This allows me to access the limit value using: Entity.LIMIT To achieve this, I rely on babel and use the plugin-proposal-class-properties. In m ...

Placing an absolutely positioned element on top of other elements

Currently, I am working on a frontendmentor website and encountering difficulty in positioning the shopping cart div above all the other elements. Initially, I attempted to use z-index for this purpose, but it seems that it does not work with elements havi ...

The scope of this variable in Node.js results in an undefined response

Have you ever noticed the difference in behavior when executing JavaScript code in Google Chrome's console compared to running the same logic in a file using Node.js? function foo() { console.log( this.bar ); } var bar = "global"; foo(); In Chr ...

Tips for utilizing global functions in VUE 2 CLI crowd

I have multiple components that require the same functions. Is there a way to avoid duplicating the code in each component and instead use it globally...? Even if I put the function in the App.vue, it still isn't accessible in the components. ...

Interactive questioning system using Javascript/jQuery for Quick Responses

Hi there! I'm new to StackOverflow and a bit of a beginner when it comes to javascript/jquery. My current project involves creating a chat interface that looks like SMS text messages. Right now, I have users inputting text and using javascript to disp ...