Error message of V-IF and V-for mutually exclusive codes in Vue project

Never use V-IF and V-for on the same element at the same time.

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

We tend to do this in two common situations:

To filter items in a list (such as V-for = “user in users” V-IF = “user.Isactive”). In this case, replace users with a calculated attribute (such as activeusers) to return the filtered list.

computed: {
  activeUsers: function () {
    return this.users.filter((user) => {
      return user.isActive
    })
  }
}


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

To avoid rendering lists that should have been hidden (such as V-for = “user in users” V-IF = “shouldshowusers”). In this case, move the V-IF to the container element (such as UL, OL).

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

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

Similar Posts: