[Vue Interview Questions] Why can't v-if and v-for be used together?

We first execute code like this
insert image description here

Our expectation is that the page can output various colors
insert image description here
. 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.
insert image description here
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.
insert image description here
If we don’t want the outer layer of div, we can change the div tag to template
insert image description here
result:
insert image description here
we can also write v-for outside

insert image description here
result:
insert image description here

Summarize:

  1. 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
  2. If the judgment condition appears inside the loop, filter the value that needs v-for in the computed property first

Guess you like

Origin blog.csdn.net/qq_40992225/article/details/129164585