think: HTML is a tag language, and only JS can implement judgment and looping. Templates have instructions, interpolation, and JS expressions, which can implement judgment, looping, etc. Therefore, templates are not HTML, so templates must be converted into some kind of JS code. How is this compilation performed? Analysis: Template compilation is the process of compiling a template into a render function. This process can be roughly divided into three stages: 1. parse The parser mainly converts template strings into Template strings: <div> <p>{{message}}</p> </div> element ASTs AST refers to the abstract syntax tree and is similar to { tag: "div" // Node type (1 label, 2 text node containing literal expression, 3 normal text node or comment node) type: 1, // static root node staticRoot: false, // Static node static: false, plain: true, // Reference to the parent node element description object parent: undefined, // Only when the node type is 1, there will be an attrsList attribute, which is an object array that stores the original HTML attribute name and value attrsList: [], // Same as above, the difference is that attrsMap stores the html attribute name and value in key-value pairs: attrsMap: {}, //Stores the element description object of all child nodes of this node children: [ { tag: "p" type: 1, staticRoot: false, static: false, plain: true, parent: {tag: "div", ...}, attrsList: [], attrsMap: {}, children: [{ type: 2, text: "{{message}}", static: false, // When the node type is 2, the object will contain the expression expression: "_s(message)" }] } ] } 1.1 Rules for interceptionMainly by judging the value of html.indexof('<') in the template to determine whether to intercept the tag or the text. The interception process: String part `<div><p>{{message}}<p></div>` 1.2 Interception process partFirst interception
/** To sum up, match tags, extract attributes, and establish hierarchies*/ // After the above matching, the remaining string is: `<p>{{message}}<p></div>` Second interception /** Same as above*/ // After the above matching, the remaining string is: `{{message}}</p></div>` The third interception
For example: /** To sum up, determine the type and intercept the text*/ // After the above matching, the remaining string is: `</p></div>` Fourth interception
/** To sum up, match the label and determine the level*/ // After the above matching, the remaining string is: `</div>` The fifth interception/** Same as above*/ Finish 1.3 Parser Summary
2. optimize The optimizer's main function is to optimize the static content of the generated AST and mark static nodes. In order to re-render each time, there is no need to create new nodes for the static subtree, and 2.1 Static NodesTraverse the AST syntax tree, find all static nodes and mark them function isStatic(node) { // expression if (node.type === 2) { return false } //text if (node.type === 3) { return true } /** 1. Dynamic binding syntax cannot be used, that is, the tag cannot have attributes starting with v-, @, or :; It can only be one */ return !!(node.pre || ( !node.hasBindings && !node.if && !node.for && !isBuiltInTag(node.tag) && isPlatformReservedTag(node.tag) && !isDirectChildOfTemplateFor(node) && Object.keys(node).every(isStaticKey) )) } 2.2 Static root nodeTraverse the tree after the above steps, find the static root node, and mark it 2.3 Optimizer Summary
3. generate code generatorThe function of the code generator is to generate a code string through the AST syntax tree. The code string is packaged into the rendering function. After the rendering function is executed, a vnode can be obtained. 3.1 JS with syntax Using with can change the way to search for free variables in {}, and search for free variables in {} as attributes of const obj = {a: 100, b: 200} with(obj) { console.log(a) console.log(b) // console.log(c) // will report an error} Code string Parse the element ASTs generated by parse and concatenate them into strings with(this){return _c('div',_c('p',[_v(message)])])} Get the render function: /** The code string can get the render function of the current component through new Function('code string')*/ const stringCode = `with(this){return _c('div',_c('p',[_v(message)])])}` const render = new Function(stringCode) To view different instructions, interpolation, and JS expressions, you can use const compiler = require('vue-template-compiler') // interpolation const template = `<p>{{message}}</p>` const result = compiler.compile(template) console.log(result.render) // with(this){return _c('p',[_v(_s(message))])} Vue source code to find the meaning of the abbreviation function The source code for template compilation can be found in the `vue-template-compiler` [2] package function installRenderHelpers(target) { target._c = createElement // Tag v-once target._o = markOnce // Convert to Number type target._n = toNumber // Convert to string target._s = toString // Render v-for target._l = renderList // Render normal slots and scoped slots target._t = renderSlot // Render static nodes through staticRenderFns target._m = renderStatic // Get the filter target._f = resolveFilter // Check keyboard event keycode target._k = checkKeyCodes target._b = bindObjectProps // Create a text vnode target._v = createTextVNode // Create an empty vnode target._e = createEmptyVNode target._u = resolveScopedSlots target._g = bindObjectListeners // Processing modifier target._p = prependModifier } Summary: Vue scaffolding will use The parsing process is to intercept the string in small segments, and then maintain a stack to save the DOM depth. When all the strings are intercepted, a complete AST is parsed. The optimization process is to recursively mark all nodes to indicate whether they are static nodes, and then recursively mark the static root nodes again. The code generation stage is to recursively generate a string of function execution code. The recursive process calls different generation methods according to different node types. This is the end of this article about the details of vue template compilation. For more relevant vue template compilation content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future! You may also be interested in:
|
<<: Docker Compose installation methods in different environments
>>: Implementation of scheduled backup in Mysql5.7
When you install MySQL, you will be given an init...
It is difficult to find good image material websi...
1. Download and decompress MySQL 8.0.20 Download ...
This article shares the specific code for canvas ...
Table of contents About Triggers Use of triggers ...
If we introduce the nesting rules of basic HTML w...
Wired network: Ethernet Wireless network: 4G, wif...
Download and install. First check whether there i...
In the vue scaffolding, we can see that in the ne...
Preface In the previous article Two data types in...
Table of contents 1. Background 2. Local custom i...
This article shares the specific code of Vue recu...
I usually like to visit the special pages or prod...
Preface When it comes to database transactions, a...
1. Concept 1. The difference between hot backup a...