Skip object items if the value is null

Viewed 120867

I have a nested for ... in loop in vue js. What I'm trying to to is to skip elements if the value of the element is null. Here is the html code:

<ul>
    <li v-for="item in items" track-by="id">
        <ol>
            <li v-for="child in item.children" track-by="id"></li>
        </ol>
    </li>
</ul>

null elements may be present in both item and item.children objects.

For example:

var data = {
   1: {
      id: 1,
      title: "This should be rendered",
      children: {
          100: {
              id: 100,
              subtitle: "I am a child"
          },
          101: null
      }
   },
   2: null,
   3: {
       id: 3,
       title: "Should should be rendered as well",
       children: {}
   }
};

With this data data[1].children[101] should not be rendered and if data[1].children[100] becomes null later it should be omitted from the list.

P.S. I know this is probably not the best way to represent data but I'm not responsible for that :)

5 Answers

I would advise you against using v-if and v-for in the same element. What I found worked and didn't affect performance is this :

<li v-for="(value, key) in row.item.filter(x => x !== null)" :key="key"{{value}}</li>

You just need to run the filter function on the array you are going through. This is a common use in c# and found it was no different in JavaScript. This will basically skip the nulls when iterating.

Hope this helps (3 years later).

VueJs style guide tell us to :

"Never use v-if on the same element as v-for."

How to handle v-if with v-for properly according to the vue style guide :

<ul v-if="shouldShowUsers">
  <li
    v-for="user in users"
    :key="user.id"
  >
    {{ user.name }}
  </li>
</ul>

See more on how to handle v-if with v-for here : https://v2.vuejs.org/v2/style-guide/#Avoid-v-if-with-v-for-essential

Related