Home > Back-end >  vuetify data table passing an item from parent to child to colour a field
vuetify data table passing an item from parent to child to colour a field

Time:08-21

Learning Vuetify and Vuetify (Loving both) but come across an issue I can't figure out so would appreciate someone sharing best practice please

I have created a component that contains a vuetify datatable and I pass the titles and items via props from a parent to the child, so far so good

The bit I can't figure out is that I want to loop through a specific field (the example I am using is item.calories as per the docs) and run a function over it.

I assume I pass the item.calories field as a prop but how do I then send that to a function

in my parent I pass to my DataTable component as follows

<DataTable 
:headers="headers" 
:content="content" 
title="This is my data table title" 
:myCalories="content.calories" <-- This bit is causing me the issue

/>

How in my DataTable component can I change the below to use the :myCalories prop, or is there a better approach I could consider?

<template v-slot:[`item.calories`]="{ item }">
  <v-chip
    :color="getColor(item.calories)"
    dark
  >
    {{ item.calories }}
  </v-chip>
</template>

My function

methods: {
  getColor (calories) {
    if (calories > 400) return 'red'
    else if (calories > 200) return 'orange'
    else return 'green'
  },
},

I did wonder if I should run the function in the parent first and pass the result over but if you could advise on the best practice way to achieve the above it would be very much appreciated

Gibbo

CodePudding user response:

I'm not sure it this will help but I had a similar problem and ended up using the body slot of the v-data-table and redefined my whole table.

This workaround could help you but this is certainly not the best approach to do it

        <template v-slot:body="{ items, headers }">
            <tbody>
                <tr v-for="item in items" :key="item.name">
                    <td v-for="column in headers" :key="column.value">
                        <div v-if="column.value === 'calories'" :style="getColor(item.calories)">
                              {{ item[column.value] }}
                        </div>
                        <div v-else>
                            {{ item[column.value] }}
                        </div>
                    </td>
                </tr>
            </tbody>
        </template>

Here is the codepen example https://codepen.io/taghurei-the-reactor/pen/YzaBNxw?editors=1111

  • Related