Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue - passing v-for index from parent to child component

I've done the research but can't find a good answer. My parent and child component code is below. How do I pass the index for the v-for loop in the parent to the child component for use there? I want to hide any of the gauges past #4 for mobile screens, but show all of them on a desktop.

Parent:

<div class="col-md-8 col-xs-6">
    <div class="row flex-nowrap">
        <data-block 
            v-for="(gauge, index) in device.gauges" 
            :metric="gauge.metric" 
            :value="gauge.value" 
            :unit="gauge.unit" 
            :alarm="gauge.alarm" 
            :idx="index">
        </data-block>
    </div>
</div>

Child:

app.component('data-block', {
    props: ['alarm', 'metric','value','unit','idx'],
    template: `<div v-bind:class="'col card px-0 text-center border' + ((alarm) ? ' border-danger':' border-success') + ((idx > 3) ? ' d-none d-md-block':'')">\
    <div class="card-header p-1">{{metric}}</div>\
        <div class="card-body p-1 align-middle">\
            <h1 class=" text-center display-1 font-weight-normal text-nowrap">{{value}}</h1>\
        </div>\
    <div class="card-footer p-1">{{unit}}</div>\
</div>`,
    created: ()=> console.log(this.idx)  //yields "undefined"
})
like image 360
Daemach Avatar asked Nov 19 '25 10:11

Daemach


1 Answers

You're passing the idx prop correctly, but Instead of checking its value inside created hook, try displaying it in the template instead, to make sure it's not an issue with timing (it might not be defined when the child component is created):

<div>{{idx}}</div>

Also, to make the code easier to read and write, I would suggest you to move the static classes to class attribute and the dynamic classes to v-bind:class attribute, and also make it multiline:

template: `
 <div 
   class="col card px-0 text-center border"
   :class="{
     'd-none d-md-block': idx > 3,
     'border-danger': alarm,
     'border-success': !alarm
   }"
 >
 ...
`
like image 177
AlekseyHoffman Avatar answered Nov 21 '25 04:11

AlekseyHoffman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!