[Vuejs]-Wrapper element for for loop

4👍

The only difference I spot between the first and the third options is that you’d wrap each list item in an additional div. You don’t need those wrappers unless you want to use this nesting for styling purposes.

Your example is perfectly fine. Just make sure ids you use for keys are unique.

Also avoid using v-if and v-for on the same element and rather add v-if on the parent

👤hurrii

0👍

Yours is fine, all of them indeed are going to work well, but the third one may have problems with custom css, since it’s a wrapper for the tag.

The template is an alternative as it is stated in the docs.

You’ve set the key at the li tag, as long as you’re following the guide for mantaining state with keys, it’s fine.

0👍

I think you should always put a key property in your for loop.

Say you have nothing to work with for an ID (some item.name could potentially be duplicated?) just use this:

<div v-for="(item, index) in items)" :key="index">
  {{ item.name }}
</div>

index in this case is just the index of the items array.

0👍

So yours will be rendered like:

<ul class="nav">
    <li class="nav-item" :key="navLink.id">
        <a class="nav-link" :href="navLink.url">{{ navLink.name }}</a>
    </li>

    ...

    <li class="nav-item" :key="navLink.id">
        <a class="nav-link" :href="navLink.url">{{ navLink.name }}</a>
    </li>
</ul>

Whereas the third one will be:

<ul class="nav">
    <div :key="navLink.id">
        <li class="nav-item">
            <a class="nav-link" :href="navLink.url">{{ navLink.name }}</a>
        </li>
    </div>

    ...

    <div :key="navLink.id">
        <li class="nav-item">
            <a class="nav-link" :href="navLink.url">{{ navLink.name }}</a>
        </li>
    </div>
</ul>

I would say it’s a bit verbose to wrap a <li> inside a <div> in each one of them.

👤KienHT

Leave a comment