10

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?

3 Answers 3

10

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>
Sign up to request clarification or add additional context in comments.

3 Comments

I've forget about this!! Btw, you saved my night @Randall, thanks +1 for the question also
this quickly turns into v-else-if hell if each column is different in terms of what elements it contains and has action buttons etc etc, any better method ?
In this case you should probably move that rows to subcomponents.
3

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>

2 Comments

No, this has nothing to do with it. The expression "must immediatly follow" refers to the HTML elements of the same level. Wahtever is nested inside, does not matter on that context. Only the v-if on the same level is the problem, as yariiash explained above. Other directives (v-on etc.) would be fine.
Thanks. However, using v-show works well with the OP's example.
1

yariash is right about the v-if and v-for. You could do as he suggested or just change the v-else to the reverse of the v-if, i.e. v-if="!my_tasks.length".

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.