Find the answer SRC \compiler\codegen\index.js in the vue2 source code

  if(el.staticRoot && ! el.staticProcessed) {return genStatic(el, state)
  } else if(el.once && ! el.onceProcessed) {return genOnce(el, state)
  } else if(el.for && ! el.forProcessed) {return genFor(el, state)
  } else if(el.if && ! el.ifProcessed) {return genIf(el, state)
  } else if (el.tag === 'template'&&! el.slotTarget && ! state.pre) {return genChildren(el, state) || 'void 0'
  } else if (el.tag === 'slot') {
    return genSlot(el, state)

Copy the code

From the source can be clearly seen, VUE internal is the first v-for processing, and then v-if processing.

For example, a list is an array, and each element is an object with a flag(Boolean :true or false) key that controls whether the object data is displayed

<p v-for="(item, index) in list" :key="index" v-if="item.flag">
Copy the code

So inside vUE, a loop is executed to determine whether the flag is displayed or not. Whether it is displayed or not, it is looped, which can be very performance consuming.

conclusion

  1. It is clear that v-for is parsed before V-if.
  2. If it happens at the same time, each render will execute a loop to determine the condition first, which is inevitable anyway, wasting performance.

To optimize the

  1. You can nest a template layer on the outer layer, perform v-if or V-for operations on this layer, and then perform another operation within the template
  2. If you have an example like the one above, you can filter out the data to render using a computed function, and then render the corresponding computed list.