Search code examples
vue.jsvue-componentrenderingrender

v-for loop throws TypeError: Cannot read property of null in VueJS application


I am developing a VueJs application which keeps throwing an error I can't determine the cause of.

<v-chip v-if="topic" v-for="(tag, iii) in topic.tags" :key="iii"
    @click:close="removeTag(tag.id)" close
    color="primary" text-color="white" class="mr-1">{{ tag.name.en }}</v-chip>

This throws the following error:

user-dashboard.js:75858 TypeError: Cannot read property 'tags' of null

Normally this error is caused by the data being specified not being initially available when the component first renders, however I have included the v-if directive to prevent this. The loop renders the components just fine however the error still remains.

What else could be the cause of this, and why are the components still properly rendering?


Solution

  • You should move v-if directive into wrapper element.

    <template v-if="topic">
      <v-chip v-for="(tag, iii) in topic.tags" :key="iii"
        @click:close="removeTag(tag.id)" close
        color="primary" text-color="white" class="mr-1">{{ tag.name.en }}</v-chip>
    </template>
    

    https://v2.vuejs.org/v2/guide/conditional.html#v-if-with-v-for

    When used together with v-if, v-for has a higher priority than v-if.