“This is the 23rd day of my participation in the First Challenge 2022. For details: First Challenge 2022”
Vue.js source code analysis – parse
The parse parser parses a template into an abstract language tree (AST). Only after the template is parsed into an AST can it be used to optimize or generate code strings.
Template compilation process baseCompile
Before we learn about the parse function, we need to know how and when it is called
BaseCompile: SRC/compiler/index.js baseCompile: SRC/compiler/index.js baseCompile: SRC/compiler/index.js
- call
parse
Convert the template into an AST abstract syntax tree, and thenOptimize the abstract syntax tree - call
generate
The abstract syntax tree generates js code in string form - Returns an object containing the following data contents:
ast
render
(Rendering function) (not hererender
Function, but a string of data, needstoFunction
To function form)staticRenderFns
(Static render function, generate static)
Parse functions
- src\compiler\index.js
- Convert the template to
ast
Abstract syntax tree - Abstract syntax tree, used to describe code structure in a tree-like manner
const ast = parse(template.trim(), options) Copy the code
- Convert the template to
- src\compiler\parser\index.js
parse() Copy the code
Tool Page Recommendation
View the AST tree
Processing of structured instructions
- V-if ultimately generates the unit expression
// src\compiler\parser\index.js
// structural directives
// Structured directives
// v-for
processFor(element)
processIf(element)
processOnce(element)
// src\compiler\codegen\index.js
export function genIf (el: any, state: CodegenState, altGen? :Function, altEmpty? : string) :string {
el.ifProcessed = true // avoid recursion
return genIfConditions(el.ifConditions.slice(), state, altGen, altEmpty)
}
// Finally call genIfConditions to generate ternary expressions
Copy the code
- V-if final compilation result
ƒ anonymous(
) {
with(this){
return _c('div', {attrs: {"id":"app"}},[
_m(0),
_v(""), (msg)? _c('p',[_v(_s(msg))]):_e(),_v(""),
_c('comp', {on: {"myclick":onMyClick}})
],1)}}Copy the code
V-if/V-for structured directives can only be processed at compile time, and if we want to process conditions or loops in the render function we can only use if and for in JS
Vue.component('comp', {
data: () {
return {
msg: 'my comp'
}
},
render (h) {
if (this.msg) {
return h('div'.this.msg)
}
return h('div'.'bar')}})Copy the code
Parse functions
The parse function iterates through the template string and converts the HTML template string into an AST object. The HTML property page instructions are stored in the AST properties