Home > Software design >  Vuetify Data-Table Header array not accepting empty child associations
Vuetify Data-Table Header array not accepting empty child associations

Time:12-05

I have a data-table using Vuetify that passes a localAuthority prop from a rails backend. It all works really well until I pass an empty child association (nested attribute). In this case 'county':

<script>
  import axios from "axios";
  export default {
    name: 'LocalAuthorityIndex',
    props: {
      localAuthorities: {type: Array, default: () => []},
      counties: {type: Array, default: () => []},
      localAuthorityTypes: {type: Array, default: () => []}
    },
    data() {
      return{
        search: '',
        dialog: false,
        testmh: 'hello',
        dialogDelete: false,      
        headers: [
          { text: 'Name', align: 'start', value: 'name' },
          { text: 'ONS Code', value: 'ons_code' },
          { text: 'ID', value: 'id' },
          { text: 'Population', value: 'population' },
          { text: 'county', value: 'county.name' },
          { text: 'Website', value: 'website' },
          { text: 'Actions', value: 'actions', sortable: false },
        ],

So in the example above it works as long as all records have a county association (belongs_to). However, if one record does not have a 'county' associated with it then I get the following error:

[Vue warn]: Error in render: "TypeError: Cannot read properties of undefined (reading 'name')"

I have tried lots of things like adding in a conditional statement like below:

      { text: 'county', value: ('county.name' ? 'county.name' : nil )},

But nothing seems to work.

CodePudding user response:

According to your <v-data-table> code at Codepen, I see that you are overriding default table item slots with your own.

Your error are from this part of code:

...
<template #item.county.name="{ item }">
  <a :href="'/counties/'   item.county_id">
    {{ item.county.name }}
  </a>
</template>
...

Take a look at first string. #item.county.name is a short form of v-slot:item.county.name and comes from one of your strings in headers array:

...
{ text: 'county', value: 'county.name' },

So there's no error, this part are correctly parsed by vuetify library even when your item will not contain any county.

The error is in 3rd string of the above code. You are trying to print name of county without checking its existence. That's why you are getting ...Cannot read properties of undefined... error.

I guess you may fix your issue this way:

<template #item.county.name="{ item }">
  <a :href="'/counties/'   item.county_id">
    {{ item.county ? item.county.name : 'No name' }}
  </a>
</template>

Of course, if you need to hide your link to counties in this case, you may also add v-if (or v-show) into a tag.

I also created a small Codepen with some static data. Take a look into item.name.text slot in this playground, maybe it will help you to understand similar object associations.

  • Related