V-if/V-for instructions are frequently used in daily development. In this article, we’ll go through the first four template compilation articles, and finally the CodeGen process, by analyzing how Vue handles these two instructions.

parseHTML

The V-if directive is processed twice when the Template string is parsed one by one using the re

First time: start(processIf)

V – if logic

1. Add the if attribute to the element, whose value is the expression corresponding to v-if

2. Call addIfCondition to add the ifCondition attribute to the element, whose value is an array, and push the expression into the array. The elements of the array are objects with the exp property and the block property. The values are the expression and the currently parsed element, respectively.

V – else – if logic

1. Add the elseif attribute to the element with the expression corresponding to v-else-if

V – else logic

1. el.else = true

Second: end(closeElement)

The processIfConditions are called when the Element is closeted.

In addition, elements with v-else-if/ V-else directives are not pushed into the children array of the parent element.

ProcessIfConditions logic

1. Find the element next to the current element that is not a text node (Vue ignores text nodes)

  1. ** If the previous element has an if instruction: ** Take the v-else-if instruction expression and build it with the element into an object, pushing it into the ifCondition array with the V-if element

Note:

1. V-if/V-else-if/V-else elements are all flat

2. V-else-if/V-else elements do not have parent-child relationships with their parents

3. The element with the V-if instruction has the ifCondition attribute, which is an array. The array stores the corresponding elements of the V-if/V-else-if instruction in turn.

optimize

MakeStatic can do to ifConditions processing/makeStaticRoot, core is processing block elements of an array element.

codegen

The generate function generates the string and takes the PARSING generated AST node as an argument.

Call genElement to generate the code string.

The last thing that is returned is the with function, which takes this, which is actually the VM instance. The scope inside the with function is the VM instance.

genElement

The function logic is long, so I’ll just look at genIf

genIf

Add tag to EL, optimize

genIfConditions

The core is to call this function recursively, each time fetching the elements from scratch from their ifCondition array and generating a string.

The important thing to note here is that in the if(condition.exp) branch of the logic is the string returned

The last

The string returned by codeGen with strings such as _c()/_t(). These are called when the component is rendered.

The values are: \ SRC \core\instance\render-helpers

The following important functions were analyzed when parsing events/slots

Reference: ustbhuangyi. Making. IO/vue – analysi…