【js】vue 2.5.1 源码学习 (十一) 模板编译compileToFunctions渲染函数
大体思路(九)
本节内容:
1. compileToFunctions定位
1 1. compileToFunctions定位 2 ==> createCompiler = createCompilerCreator(function beasCompile(){}) // 创建编译器的编译器 编译器的爷爷。 3 ==> beasOptions 编译器默认预留选项 4 ==> createCompiler(beasOptions) 创建一个编译器。返回一个对象 5 ==> { compile: function{} ,conpileToFunctions:function{} } 6 ==> compileToFunctions(template,{用户配置和兼容},this) 7 ==> createCompilerCreator(beasCompile){ 8 return function createCompiler(beasOptions){ 9 function compiler(template,options){ 10 // 编译器核心方法 11 } 12 return { 13 compile: compiler, 14 conpileToFunctions: createComilpeToFunctionFn(compiler) 15 } 16 } 17 } 18 ==> createComilpeToFunctionFn(compile){ 19 // 缓存对象 存储 编译结果 20 var cache = Object.create(null) 21 return function comilpeToFunctions(template,options,vm) { 22 try{ 23 new Function('return 1') 24 }catch(e){ 25 if(e.toString().match(/unsafe-eval|csp/)){ 26 console.error('您当前的环境禁止不安全评估的内容安全策略,模版编译无法在此环境中工作') 27 } 28 } 29 var key = template 30 // 缓存作用,编译过后不重复编译 31 if(!cache[key]){ 32 return cache[key] 33 } 34 var compiled = compile(template,options) 35 /// comilped.errors 错误信息 compiled.tips 提示信息 36 if(){} if(){} 37 var res = {} 38 var fnGenErrors = [] 39 res.render = createFuntion(compiled.render,fnGenErrors); 40 res.staticRenderFns = compiled 41 return res; 42 43 } 44 } 45 ==> compiler(template,options){ 46 finalOptions = 47 errors = [] tips = [] 48 // if(options) 检测用户有那些自定义配置,最终扩展到 finalOptions 49 var compiled = beasCompile(template,finalOptions) 50 errors tips 51 return compiled; 52 } 53 ==> beasCompile(template,options){ 54 // 把模版解析成抽象的语法树(AST) parse 函数 55 // 根据给点的AST 生成目标平台需要的代码 “函数题的字符串” generate() 函数new Function() 56 var ast = pares() 57 var code = generate(ast,options); // 函数体字符串 58 return { 59 // ast:ast, 60 render:code.render, // 渲染函数 61 // staticRenderFns: code.staticRenderFns 62 63 } 64 } 65 ==> createFuntion(code,error){ 66 try{ 67 new Function(code) 68 }catch(){ 69 70 } 71 }2. compileToFunctions 作用 3. 模版编译代码组织结构 本节将新内容分开写到compileToFunctions 分析学习后,在合并到vue.js,如下是compileToFunctions.js compileToFunctions.js index.html代码如下
1 2 3 4 5 6 7第九课 8 9 1011 12 1314 15 16 48 49
如有问题或者疑惑,欢迎评论。