Example Analysis of vue template compilation
This article shares with you the content of a sample analysis of vue template compilation. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.
Think about:
Html is a tag language, only JS can achieve judgment, loop, while the template has instructions, interpolation, JS expression, can achieve judgment, loop, etc., so the template is not html, so the template must be converted to some kind of JS code, how is this compilation carried out?
Parsing:
Template compilation is the process of compiling template into render functions, which can be roughly divided into three phases:
1. Parse parser
The parser mainly converts the template string into element ASTs.
Template string:
{{message}}
Element ASTs
AST is an abstract syntax tree, similar to Vnode, which uses JavaScript objects to describe the tree representation of nodes.
{tag: "div" / / type of node (1 tag, 2 text node containing literal expression, 3 plain text node or comment node) type: 1, / / static root node staticRoot: false, / / static node static: false, plain: true, / / reference to the object described by the parent node element parent: undefined, / / the attrsList attribute is available only if the node type is 1 It is an array of objects that stores the original html attribute name and value attrsList: [], / / ditto The difference is that attrsMap stores the html attribute name and value attrsMap: {}, / / stores the element description object children: [{tag: "p" type: 1, staticRoot: false, static: false, plain: true, parent: {tag: "div",...}, attrsList: [] AttrsMap: {}, children: [{type: 2, text: "{{message}}", static: false, / / when node type is 2 The expression expression that the object will contain: "_ s (message)"}]}]} 1.1 intercepted rules
Mainly by judging the html.indexof ('