Search code examples
javascriptcssvue.jsdatatableprimevue

PrimeVue DataTable Row Color based off of Column Item


So I have a PrimeVue DataTable that is structured like so:

<DataTable value="info">
  <Column header="Name" field="name" />
  <Column header="Desc." field="desc" />
  <Column header="Date" field="date" />
</DataTable>

The value of the DataTable is occupied by the array, "info", which consists of information pulled from an API. I need certain rows within the DataTable to appear either red or green based on the property "desc" within "info"; I have attempted to go about it in these ways:

Using rowStyle

<DataTable value="info" :rowStyle="desc === 'Disconnected' ? 'color:red' : null">
  <Column header="Name" field="name" />
  <Column header="Desc." field="desc" />
  <Column header="Date" field="date" />
</DataTable>

I have used multiple variations of rowStyle, but the primary issue I am having is accessing variables within the DataTable when implementing said style. I suppose another method could be using a ColumnGroup and then assigning a <Row> value, then modifying it with the respective color change?

Any help? Thanks!


Solution

  • When you provide a function to :rowStyle or :rowClass, the first argument is row's data, which you can use to decide the color.

    <DataTable :rowClass="({ desc }) => desc === 'Disconnected' ? 'text-red-500': null">
      ...
    </DataTable>
    

    Similarly, inside a <Column>'s #body slot, you will find data and field properties, which can be used to decide the color:

    <Column field="desc" header="Desc.">
      <template #body="{ field, data }">
        <div :class="data[field] === 'Disconnected' ? 'text-red-500' : null">
          {{ data[field] }}
        </div>
      </template>
    </Column>
    

    Docs example.

    You might want to write the function inside <script> and reference it in template, as shown in the example, instead of writing it inline, as I did above. Both work.