2

I'm trying to add HTML to headers in a Vue table. Knowing the key of the field I can do something like this:

<template v-slot:head(my_key)="data">
<span v-html="data.field.label" />
</template>

However, my table will have an unknown number of columns each with unknown keys to start (pulled in through axios). Is there a way to dynamically set my_key after I retrieve all of the keys from my server?

Dan
  • 59,490
  • 13
  • 101
  • 110
Eric
  • 1,209
  • 1
  • 17
  • 34

2 Answers2

4

You can use dynamic slot names to target the header slot with a variable. Assuming my_key in your pseudo-code example above is the name of a variable, then your example could be rewritten with a template literal:

<template v-slot:[`head(${my_key})`]="data">

You can then use the table's fields array, or any array of keys, with a v-for to target all of the table header slots:

<template v-for="field in fields" v-slot:[`head(${field})`]="data">
  <span v-html="data.field.label" />
</template>
data: () => ({
  fields: ['a', 'b', 'c']
})
tony19
  • 125,647
  • 18
  • 229
  • 307
Dan
  • 59,490
  • 13
  • 101
  • 110
0

Just for the sake of completion and for people that might be looking at older code (and perhaps struggling with the syntax as I was), an alternative solution to @Dan's one, based on a depreciated syntax could be something like:

<template
  v-for="{key} in fields"
  :slot="`HEAD_${key}`"
  slot-scope="{label}"  
>
  <span v-html="label" />
</template>
tony19
  • 125,647
  • 18
  • 229
  • 307
rubebop
  • 392
  • 1
  • 7
  • 17