Disadvantages and solutions of using v-if and v-for in vue
It is not recommended to use both v-if and v-for as the priority of both is not obvious.
When v-if and v-for exist on an element at the same time, v-if will be executed first. This means that the v-if condition will not be accessible to the variable alias defined in the v-for scope:
<!-- This throws an error,Because of the attributes todo at this time Not defined on this instance --> <li v-for="todo in todos" v-if="!"> {{ }} </li>
Newly wrapping a layer of <template> and using v-for on it can solve this problem (this is also more obvious and easy to read):
<template v-for="todo in todos"> <li v-if="!"> {{ }} </li> </template>
Otherwise, v-for is higher priority than v-if. If there are more array elements traversed but fewer v-if conditions, performance will be wasted. It is recommended not to use it. Moreover, every time the page is refreshed, such low-performance code will be executed.
If v-if is in v-for, you can use computed to solve the problem. Filter the array through the array method filter, and v-for directly loops to calculate the results of the attributes, so you don't need to use v-if. Moreover, computed has a cache, which means that when its dependencies have not changed, the corresponding functions of the computed attributes will no longer be executed, which will improve performance.
If v-if is outside v-for, you can use the <template> tag.
Why v-if and v-for cannot be used together and the solution
reason:
Since v-for has higher priority than v-if, v-if will be used every time the loop. v-if controls the display and hiding of elements by creating and destroying dom elements, so it will constantly create and destroy elements, causing page stuttering and performance degradation
Solution:
The first one: put v-if and v-for in different tags respectively
<ul v-if="active"> <li v-for="(item, index) in list" :key="inde"> <p>{{}}</p> </li> </ul>
The second type: if v-if and v-for can only be placed in the same level tag, useCalculate propertiesRenovation:
let title = "Customize" <ul v-for="(item, index) in lists(list, title)" :key="index"> <li>{{}}</li> </ul>
computed: { lists () { return (item, name) => { return (item => !== name) } } }
Both of the above methods can solve the error reported by eslint.
This is the article about the disadvantages and solutions of using v-if and v-for in vue. This is the end. For more related content on v-if and v-for in vue, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!