VUE3 Computed values inside v-data-table cells

124 views Asked by At

I am using v-data-table component in Vue3 to display tabular data. I would like to ask if its possible to let one of the table cells be a computed value or method which takes its input from other cells?

<script setup>

defineOptions({
data:()=>({
headers:[
{ key: 'calories', title: 'Calories' },
{ key: 'fat', title: 'Fat (g)' },
{ key: 'carbs', title: 'Carbs (g)' },
{ key: 'protein', title: 'Protein (g)' },
{ key: 'iron', title: 'Iron (%)' },
{ key: 'power', title: 'Power' },
],
desserts: [
{ 
 name: 'Frozen Yogurt',
 calories: 159,
 fat: 6.0,
 carbs: 24,
 protein: 4.0,
 iron: 1,
 power: << COMPUTED VALUE FROM OTHER CELLS IN SAME ROW >>,
}
],
})

</script>

<v-template>

    <v-data-table :headers="headers" :items="desserts"></v-data-table>

</template>

I tried adding numbers and calling a function both worked.

desserts: [{ 
 power:1+1
}]

and

desserts:[{
 power:fnHelloWorld()
}]

worked. but I can't figure out how i can reference values of other cells in the same row.

2

There are 2 answers

4
Second2None On

I'd probably use a ref variable that maps and calculates. Depending on your use case and if you plan on updating the original data (a computed property may not be needed or a ref)

const processedDesserts = ref(desserts.map((dessert) => {
   dessert.power = 1 + 1;
   return dessert;
}));

Then, call the mapped variable:

<v-data-table :headers="headers" :items="processedDesserts"></v-data-table>

If you do actually want a computed value that updates with your original data, I would set it with the computed value inside the object you want computed.

const processedDesserts = desserts.value.map((dessert: any) => {
  dessert.power = computed(() => dessert.calories * 10);
  return dessert;
});
0
David ROSEY On

You can acheive that using a computed value:

something like this :

<script setup>
  const headers = ref([
    { key: 'calories', title: 'Calories' },
    { key: 'fat', title: 'Fat (g)' },
    { key: 'carbs', title: 'Carbs (g)' },
    { key: 'protein', title: 'Protein (g)' },
    { key: 'iron', title: 'Iron (%)' },
    { key: 'power', title: 'Power' },
  ]);

  const desserts = ref([
    {
      name: 'Frozen Yogurt',
      calories: 159,
      fat: 6.0,
      carbs: 24,
      protein: 4.0,
      iron: 1,
    },
  ]);

  const processedDesserts = computed(() => desserts.value.map((dessert) => ({ ...dessert, power: dessert.iron + 1 })));
</script>

<template>
  <v-data-table :headers="headers" :items="processedDesserts"></v-data-table>
</template>