1. V-if and V-for have a higher priority. If they occur at the same time, how can they be optimized to achieve better performance?

Source location

url src\compiler\codegen\index.js

export function genElement (el: ASTElement, state: CodegenState) :string {
  if (el.parent) {
    el.pre = el.pre || el.parent.pre
  }

  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) {// Line 64 => for takes precedence over if
    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)
  } else {
    // ...}}Copy the code

Conclusion: Obviously V-for is resolved in preference to V-if

Test sibling vs. non-sibling comparisons (if both occur, how can they be optimized for better performance?)

<p v-for="item in items" v-if="condition"></p><! -- --><div v-if="condition"><p v-for="item in items"></p></div>
Copy the code

After peer execution

ƒ anonymous () {with (this) {return _c (' div '{attrs: {" id ":" demo "}}, _l ((children), function (the child) {return (isFolder)? _c('p',[_v(_s(child.title))]):_e()}),0)} }Copy the code

After different levels of execution

(function anonymous() {
  with (this) { return _c('div', { attrs: { "id": "demo" } }, [(isFolder) ? _c('div', _l((children), function (child) { return _c('p', [_v(_s(child.title))]) }), 0) : _e()]) }
})
Copy the code

Find that the render order is executed differently and draw the conclusion

conclusion

  1. Parsing the rendering process is to enter the loop to iterate over the numbers and then make a conditional judgment.
  2. At the same time, loops are performed before conditions are judged on each render, because loops are inevitable and waste performance. V-if judgments can be made on the outer layer and loops on the inside
  3. If conditions occur inside the loop, items that do not need to be displayed can be filtered ahead of time by calculating attributes