聊一聊v-if的实现

聊一聊v-if

首先来举个栗子

  

v-if块的内容

v-else-if块的内容

v-else块的内容

最后渲染在页面上的DOM元素只会是三个p元素中的一个。那么这是为什么咩?

Vue进行了如下转化template ---> ast ---> render函数,最后根据生成的render函数来生成相应的DOM,这里就不拓展讲了。在生成ast和render函数的时候,Vue对v-if这一类指令进行了解析。

生成AST

这一部分是将template模板转换成相应的ast语法树,这部分源码在compiler/parser/index.js下。

/*匹配if属性,分别处理v-if、v-else以及v-else-if属性*/
function processIf (el) {
  /*取出v-if属性*/
  const exp = getAndRemoveAttr(el, 'v-if')
  if (exp) {
  /*存在v-if属性*/
    el.if = exp
    /*在el的ifConditions属性中加入{exp, block}*/
    addIfCondition(el, {
      exp: exp,
      block: el
    })
  } else {
  /*不存在v-if属性*/
    if (getAndRemoveAttr(el, 'v-else') != null) {
      el.else = true
    }
    const elseif = getAndRemoveAttr(el, 'v-else-if')
    if (elseif) {
      el.elseif = elseif
    }
  }
}


/*在el的ifConditions属性中加入condition*/
function addIfCondition (el, condition) {
  if (!el.ifConditions) {
    el.ifConditions = []
  }
  el.ifConditions.push(condition)
}

这段代码所做的事情就是:如果元素中有v-if的话,就将v-if的条件取出来加入到el.ifConditions里面,如果有 v-else,v-else-if属性的话就将相应的标志位置为成true。

因为我们只把v-if的条件挂在了el.ifConditions下面,但v-else,v-else-if都还未进行处理,所以接下来需要将它们也加入进去。

      if (currentParent && !element.forbidden) {
        if (element.elseif || element.else) {
          /*当遇到当前ele有v-else或者v-elseif属性的时候,需要处理if属性,在其上级兄弟元素中必然存在一个v-if属性*/
          processIfConditions(element, currentParent)
        }
      }
      
/*处理if条件*/
function processIfConditions (el, parent) { 
    //找到当前元素的上一个兄弟元素
  const prev = findPrevElement(parent.children)
  if (prev && prev.if) {
    addIfCondition(prev, {
      exp: el.elseif,
      block: el
    })
  } else if (process.env.NODE_ENV !== 'production') {
    warn(
      `v-${el.elseif ? ('else-if="' + el.elseif + '"') : 'else'} ` +
      `used on element <${el.tag}> without corresponding v-if.`
    )
  }
}

当遇到当前ele有v-else或者v-elseif属性的时候,需要处理if属性,在其上级兄弟元素中必然存在v-if属性,然后将当前元素的else-if上表达式添加到上个元素的ifConditions上。
转换后的ast树

{
  type: 1,
  tag: 'div',
  plain: false,
  children: [{
    type: 1,
    tag: 'p',
    children: [{
      text: 'v-if块的内容',
      type: 3
    }]
    if: 'value == 1',
    ifConditions: [{
      exp: "value == 1",
      block: {
        type: 1,
        tag: 'p',
        children: [{
          text: 'v-if块的内容',
          type: 3
        }],
        if: 'value == 1',
        ifConditions: [],
        plain: true
      }
    }, {
      exp: "value == 2",
      block: {
        type: 1,
        tag: 'p',
        children: [{
          text: 'v-else-if块的内容',
          type: 3
        }],
        elseif: 'value == 2',
        plain: true
      }
    }, {
      exp: undefined,
      block: {
        type: 1,
        tag: 'p',
        children: [{
          text: 'v-else块的内容',
          type: 3
        }],
        else: true,
        plain: true
      }
    }]
  }]
}

ast树中的转换已经进行完毕了,接下来要根据刚刚挂载这颗ast树上的相应属性。来生成相应的render函数了。

生成render函数

这部分源码在compiler/codegen/index.js下。

function genElement (el: ASTElement): string {
 ******************************
  else if (el.for && !el.forProcessed) {
    /*处理v-for*/
    return genFor(el)
  } else if (el.if && !el.ifProcessed) {
    /*处理v-if*/
    return genIf(el)
  }
  ****************************
}

其中genIf函数就是对于v-if的处理

function qizhon genIf (el: any): string {
  /*标记位,避免递归处理*/
  el.ifProcessed = true
  return genIfConditions(el.ifConditions.slice())
}

/*处理if条件*/
function genIfConditions (conditions: ASTIfConditions): string {
  if (!conditions.length) {
    return '_e()'
  }

  const condition = conditions.shift()
  if (condition.exp) {
    return `(${condition.exp})?${genTernaryExp(condition.block)}:${genIfConditions(conditions)}`
  } else {
    return `${genTernaryExp(condition.block)}`
  }

  // v-if with v-once should generate code like (a)?_m(0):_m(1)
  /*v-if与v-once同时存在的时候应该使用三元运算符,譬如说(a)?_m(0):_m(1)*/
  function genTernaryExp (el) {
    return el.once ? genOnce(el) : genElement(el)
  }
}

genIfConditions函数将el上的ifConditions上收集的if,else,else-if属性进行递归处理,最后生成render函数

with(this){
    return _c('div',
    {attrs:{"id":"app"}},[
        (value == 1)?
            _c('p',[_v("v-if块的内容")])
            :(value == 2)?_c('p',[_v("v-else-if块的内容")]):_c('p',[_v("v-else块的内容")])
        ]
    )
}

最终在执行render函数时,会根据vue中绑定变量的值,来决定创建哪一部分的template

你可能感兴趣的:(聊一聊v-if的实现)