Vue officials strongly recommend not to use v-for and v-if inOn the same element
Because v-for has a higher priority than v-if, even if you only need to render part of the content through v-if, you need to traverse the entire list every time you re-render, regardless of whether the required content has occurred. Change, so not using v-for and v-if on the same element at the same time is a means to improve performance
Of course: the need to perform this type of operation is generally divided into two situations:
One, filter the items in a list
Example:
<ul>
<li
v-for="user of users"
v-if="user.isActive"
:key="user.id"
>
{
{user.name}}
</li>
</ul>
It can be rewritten like this:
Define a calculated attribute to filter the list, and then use v-for to traverse the calculated attribute
computed: {
activeUsers() {
return this.users.filter( user => {
return user.isActive
})
}
}
Change template:
<ul>
<li
v-for="user of activeUsers"
:key"user.id"
>
{
{user.name}}
</li>
</ul>
After rewriting, there are the following benefits:
- The content in the calculated attribute is recalculated only when the original list changes, and there is no need to traverse the original list every time
- Only render what you need when rendering
- Decoupling the logic of the rendering layer to improve the maintainability of the code
Second, only render the list that needs to be displayed
<ul>
<li
v-for="user of users"
v-if="showUsers"
:key="user.id"
>
</li>
</ul>
Adding the v-if judgment to its package container, you do not need to check the showUsers attribute of each item every time, but only check it once, and will not perform the v-for operation when showUsers is false
<ul v-if="showUsers">
<li
v-for="user of users"
:key="user.id"
>
</li>
</ul>