V-for and V-IF priorities

– Vue3 Template compiler

  • V-for and V-if are the same

<div v-if="isShow" v-for="item in items" :key="item">{{item}}</div>
Copy the code
export function render(_ctx, _cache, $props, $setup, $data, $options) {
  return (_ctx.isShow)
    ? (_openBlock(true), _createBlock(_Fragment, { key: 0 }, _renderList(_ctx.items, (item) = > {
        return (_openBlock(), _createBlock("div", { key: item }, _toDisplayString(item), 1 /* TEXT */))}),128 /* KEYED_FRAGMENT */))
    : _createCommentVNode("v-if".true)
Copy the code
  • V-if outside, V-for inside

<div v-if="isShow">
  <div v-for="item in items" :key="item">{{item}}</div>
</div>
Copy the code
export function render(_ctx, _cache, $props, $setup, $data, $options) {
  return (_ctx.isShow)
    ? (_openBlock(), _createBlock("div", { key: 0 }, [
        (_openBlock(true), _createBlock(_Fragment, null, _renderList(_ctx.items, (item) = > {
          return (_openBlock(), _createBlock("div", { key: item }, _toDisplayString(item), 1 /* TEXT */))}),128 /* KEYED_FRAGMENT */))
      ]))
    : _createCommentVNode("v-if".true)}Copy the code

– Vue2 Template compiler

  • V-for and V-if are the same

 <div><div v-if="isShow" v-for="item in items" :key="item">{{item}}</div></div>
Copy the code
 with(this) {
     return _c('div', _l((items), function (item) {
         return (isShow) ? _c('div', {
             key: item
         }, [_v(_s(item))]) : _e()
     }), 0)}Copy the code
  • V-if outside, V-for inside

<div v-if="isShow"><div v-for="item in items" :key="item">{{item}}</div></div>
Copy the code
with(this) {
    return (isShow) ? _c('div', _l((items), function (item) {
      return _c('div', {
        key: item
      }, [_v(_s(item))])
    }), 0) : _e()
  }
Copy the code
  • Source SRC \ compiler \ codegen \ index js 66

if(el.if && ! el.ifProcessed) {return genIf(el, state)
  } else if (el.tag === 'template'&&! el.slotTarget && ! state.pre) {return genChildren(el, state) || 'void 0'
  }
Copy the code

– summary

  • In the vue2v-forThe priority of is greater thanv-ifIn vue3v-ifPriority greater thanv-for

  • v-forWhen the priority is higher, traversing to determine whether to render will cause unnecessary operations

  • You can write with the template tag outsidev-iflogic