I'm looking for displaying bootstrap alert, if v-for return no line, it appear with v-if="!records.length", but the problem is that the alert always shown at page load!

<tbody>
 <tr v-for="record of records" :key="record.id">
  <td class="text-nowrap">{{ record.last_name }} {{ record.first_name }}</td>
  <td class="text-nowrap">{{ age(record) }}</td>
 </tr>
</tbody>
<div v-if="!records.length" id="errorMsg" class="alert alert-danger text-center" role="alert">
     nothing to show !
</div>

1 Answers

0
Matthew Vanlandingham On

As Adriano pointed out, the Vue Instance Lifecycle comes into play here. When the DOM is first created, the records data hasn't been initialized yet, meaning that !records.length will return true. To keep this from happening, initialize the records data in the created() hook. This way the data will be gathered before the DOM is rendered, so the error message will not be displayed if there are values in records.