Vuetify data table header array does not accept empty subassociations
P粉928591383
P粉928591383 2024-03-27 17:30:37
0
1
481

I have a datatable using Vuetify that passes the localAuthority attribute from a Rails backend. Everything works fine 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 will work as long as all records have county associations (belongs_to). However, if a record does not have a "county" associated with it, you will receive the following error:

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

I tried many ways, such as adding conditional statements like this:

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

But nothing seems to work.

P粉928591383
P粉928591383

reply all(1)
P粉459440991

Based on the <v-data-table> code on Codepen, I see that you are overwriting the default table entry slot with your own code.

Your error comes from this part of the code:

...

...

Look at the first string. #item.county.name is the abbreviation of v-slot:item.county.name, from one of the strings in the headers array:

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

So there is no error, even if your item does not contain any county, this part will be correctly parsed by the vuetify library.

The error occurs in the third string of the above code. You are trying to print the name of county without checking if it exists. That's why you're getting the ...Cannot read property of undefined... error.

I think you can solve your problem like this:

Of course, if you need to hide the county link in this case, you can also add v-if (or v-show) to a in the label.

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template