We first execute code like this
Our expectation is that the page can output various colors
. The above results are indeed in line with our expectations. When the flag is changed to false, there will be no content on the result page, and the above operations are all in line with our expectations.
Ask why v-if and v-for cannot be used together?
Answer: This involves the issue of priority. In vue2, the priority of v-for is higher than that of v-if, so v-for will be executed first during execution, that is, the corresponding dom node will be created. If v When -if is false, the dom node will be deleted. If it is deleted after creation, it will cause the page to freeze and waste performance.
How to avoid this situation?
v-if and v-for can be nested. For example, if you want to execute v-if first, you can create a div tag outside and write v-if into this tag.
The above code can also get the same result. But when v-if is true, our outer layer will have an extra layer of div tags.
If we don’t want the outer layer of div, we can change the div tag to template
result:
we can also write v-for outside
result:
Summarize:
- Nest template in the outer layer (page rendering does not generate dom nodes), first perform v-if judgment on this layer, and then perform v-for loop inside
- If the judgment condition appears inside the loop, filter the value that needs v-for in the computed property first