Search code examples
vue.jsvuejs2primevue

How to add links to each table entry using PrimeVue's DataTable component?


The PrimeVue library does not support this by default. The Table currently looks like this .

This is my array of products:

products: [
        {brand: "Volkswagen", year: 2012, color: "Orange", vin: "dsad231ff", url: "linkToSite"},
        {brand: "Audi", year: 2011, color: "Black", vin: "gwregre345", url: "linkToSite"},
        {brand: "Renault", year: 2005, color: "Gray", "vin": "h354htr", url: "linkToSite"},
   ]

This is the default PrimeVue DT column setup:

columns: [
            {field: 'brand', header: 'Brand'},
            {field: 'year', header: 'Year'},
            {field: 'color', header: 'Color'},
            {field: 'vin', header: 'Vin'}
        ]

This is my template code:

<DataTable :value="products">
    <Column v-for="col of columns" :field="col.field" :header="col.header" :key="col.field"></Column>
</DataTable>

Solution

  • Use a <template #body="slotProps"> to customize the appearance of cells in a <Column>.

    <DataTable ...>
      <Column field="brand" header="Brand">
        <template #body="slotProps">
          <a :href="slotProps.data.url" v-text="slotProps.data.brand" />
        </template>
      </Column>  
      ...
    </DataTable>
    

    More examples in docs.

    Inside your v-for (I haven't tested this, but it should work):

      <Column v-for="col of columns"
             :field="col.field"
             :header="col.header"
             :key="col.field">
        <template #body="slotProps" v-if="col.field === 'brand'">
          <a :href="slotProps.data.url" v-text="slotProps.data.brand" />
        </template>
      </Column> 
    

    If, for some reason, it doesn't work, please create a mcve using codesandbox.io or similar, with what you currently have, and I'll have a look into why it doesn't work for you.