Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vue.js conditional rendering in tables

I have a table populated by vue where I want to show rows if there's data, or a row with "no results" if there's no data. Here's a basic look at it in jsfiddle.

Why does the v-else row continue to show even when the v-if condition is met?

like image 424
user101289 Avatar asked Jul 27 '16 16:07

user101289


2 Answers

Unfortunately v-if and v-for are not working together. You could move v-if one level higher, like this:

<tbody v-if="my_tasks.length">
    <tr id="retriever-task-{{ index }}" v-for="(index, task) in my_tasks" >
        <td>{{ task.id }}</td>
        <td>{{ task.type }}</td>
        <td>{{ task.frequency }}</td>
        <td>{{ task.status }}</td>
        <td><i v-on:click="deleteTask(index, task.id)" class="fa fa-trash"></i></td>
    </tr>
</tbody>
<tbody v-else>
    <tr>
        <td colspan="6">No tasks found.</td>
    </tr>
</tbody>

You can also use pseudoelement template:

<template v-if="my_tasks.length">
    <tr id="retriever-task-{{ index }}" v-for="(index, task) in my_tasks" >
        <td>{{ task.id }}</td>
        <td>{{ task.type }}</td>
        <td>{{ task.frequency }}</td>
        <td>{{ task.status }}</td>
        <td><i v-on:click="deleteTask(index, task.id)" class="fa fa-trash"></i></td>
    </tr>
</template>
<template v-else>
    <tr>
        <td colspan="6">No tasks found.</td>
    </tr>
</template>
like image 68
Krzysztof Atłasik Avatar answered Sep 19 '22 17:09

Krzysztof Atłasik


From the Vuejs docs "The v-else element must immediately follow the v-if or v-show element - otherwise it will not be recognized." - https://vuejs.org/guide/conditional.html. It looks like the additional vue data binding attributes following the v-if are breaking it (e.g. v-for and v-on).

You can use v-show instead. For example:

    <tr v-show="!my_tasks.length">
      <td colspan="6">No tasks found.</td>
    </tr>
like image 44
morecchia808 Avatar answered Sep 18 '22 17:09

morecchia808