According to the vue js style guide ,
To avoid rendering a list if it should be hidden (eg v-for="user in users" v-if="shouldShowUsers"). In >these cases, move the v-if to a container element (eg ul, ol).
In my case, I am using v-for to render data in table rows but when the list is null, v-for still tries to access the null object's properties which leads to the following console error:
Error in render: "TypeError: Cannot read property 'logo' of null"
Here's my HTML code
<tbody class="list" v-if="subscribers.length > 0">
<tr v-for="(subscriber, index) in subscribers" :key="index">
<th scope="row">
<div class="media align-items-center">
<a href="#" class="avatar rounded-circle mr-3">
<img alt="subscriber.logo" :src="`/img/avatars/${subscriber.logo}`">
</a>
<div class="media-body">
<span class="name mb-0 text-sm">{{subscriber.name}}</span>
</div>
</div>
</th>
<td>{{subscriber.email}}</td>
<td>{{subscriber.licenses}}</td>
<td>{{subscriber.status}}</td>
<td class="table-actions">
<a href="#!" class="table-action" data-toggle="tooltip"
data-original-title="Edit">
<i class="fas fa-user-edit" v-on:click="loadSubscriberEdit(index)"></i>
</a>
<a href="#!" class="table-action table-action-delete" data-toggle="tooltip"
data-original-title="Delete">
<i class="fas fa-trash" v-on:click="deleteSubscriber(index)"></i>
</a>
<a href="#!" v-bind:class="computeActiveActions(index)"
:key="activeActionClassKey"
data-toggle="tooltip"
data-original-title="Delete">
<i v-bind:class="computeActive(index)" :key="activeClassKey"
v-on:click="toggleActivation(index)"></i>
</a>
</td>
</tr>
</tbody>
<tbody v-else>
<tr>
<td class="table-actions">No Subscriber found.</td>
</tr>
</tbody>
When subscribers list is null, the v-else block is rendered which works fine, however, the console still logs the above mentioned error
Error in render: "TypeError: Cannot read property 'logo' of null"
What can I do to stop v-for from trying to render if subscribers list is empty?
new Vue({ el: "#app" })
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <!-- CASE 1 --> <!--div id="app"> <table> <tbody v-if="false"> if </tbody> <tbody v-else> else </tbody> </table> </div--> <!-- CASE 2 --> <div id="app"> <table> <tbody> <template v-if="false"> if </template> <template > else </template> </tbody> </table> </div>
I know this is weird but for some reason, v-if doesn't seem to work with tbody
. Case 1 is the desired code and Case 2 is a work around
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.