Vue: v-if with array

Created on 14 Jan 2015  ·  12Comments  ·  Source: vuejs/vue

Could v-if exclude empty arrays ?
Or is there another way to do it ?

For instance, imagine the given Vue :

<section id='container'>
    <div id='list-wrapper' v-if='list << I would here mean : "if list is not empty" >>'>
        <h5>List of things</h5>
        <ul>
            <li v-repeat='item: list'>{{ item }}</li>
        </ul>
    </div>
</section>

new Vue({
    el: '#container',
    data: function () {
        return {
            list: []
        }
    },
    events: {
        'list:add': function (item) {
            this.list.push(item);
        }
    }
});

When list is an empty array, I would prefer the content of <div id='list-wrapper'></div> not to be included in the DOM.
I would prefer it to be included only when I push some items in my listarray.

Most helpful comment

<div id='list-wrapper' v-if="list.length > 0">
</div>

And here's a fiddle: http://jsfiddle.net/4t6hjwev/1/

All 12 comments

v-if: Conditionally insert / remove the element based on the truthy-ness of the binding value.

So you just need to think of a javascript expression that will evaluate to false if the array is empty...

Like checking, at any mutation of the graph, and when the array become empty, set it to false ?

No you don't have to check for array mutation, Vue will do that for you.

So how could I do it ?

<div id='list-wrapper' v-if="list.length > 0">
</div>

And here's a fiddle: http://jsfiddle.net/4t6hjwev/1/

Oh, okay, I just didn't realize I could access the array properties inside the directive.
Thanks !

<tr v-if="isVisibleDetailRow(item[detailRowId])"> show detail </tr>

here item is an array and detailRowId is contains dynamic data.

But i m getting ReferenceError: detailRowId is not defined

How its possible to handle this kind of access?

same here

Sadly v-if is very unreliable. It often gives me an undefined error.

I'm sorry to hear that.

But I have a question: What exactly are we supposed to do with that statement, posted to a two year old, closed issue with zero information about the exact problem?

<div id='list-wrapper' v-if="list && list.length > 0">
</div>
Was this page helpful?
0 / 5 - 0 ratings

Related issues

aviggngyv picture aviggngyv  ·  3Comments

6pm picture 6pm  ·  3Comments

gkiely picture gkiely  ·  3Comments

robertleeplummerjr picture robertleeplummerjr  ·  3Comments

guan6 picture guan6  ·  3Comments