-Which priority is higher between v-if and v-for?


Idea analysis:

  1. give the conclusion first
  2. Why is this so, give details
  3. What scenarios might lead us to do this, and what to do about it
  4. sum up, uplift

Sample answer:

  1. In practice, v-for and v-if should not be put together
  2. In vue2 , the priority of v-for is higher than that of v-if . Putting them together, it can be seen from the output rendering function that the loop will be executed first and then the condition will be judged. Even if we only render a small part of the elements in the list, we have to traverse the entire list every time we re-render .
  3. There are usually two situations that lead us to do this:
  • In order to filter items in a list (eg v-for="user in users" v-if="user.isActive". At this point, define a calculated property (for example activeUsers), and let it return the filtered list (for example users.filter(u=>u.isActive)).
  • To avoid rendering lists that should be hidden (eg v-for="user in users" v-if="shouldShowUsers". At this point, just v-ifmove to the container element (for example ul, ol) or wrap a layer outside template.
  1. The docs explicitly say to never use v-ifand v-forboth on the same element , which is obviously an important consideration.
  2. In the part about code generation in the source code, you can clearly see whether to process v-if or v-for first. The order of vue2 and vue3 is just the opposite, so some symptoms are different, but they cannot be written together anyway.

Guess you like

Origin blog.csdn.net/keaicll/article/details/125838640