vue 神奇的模板语法是如何实现的

626 阅读1分钟

在底层的实现上,Vue 将模板编译成虚拟 DOM 渲染函数。结合响应系统,Vue 能够智能地计算出最少 需要重新渲染多少组件,并把 DOM 操作次数减到最少。

// 输出vue替我们生成的渲染函数一窥究竟 
console.log(app.$options.render)
// 它长这个样子
(function anonymous(
){
with(this){return _c('div',{attrs:{"id":"app"}},[_c('h2',{attrs: 
{"title":title}},[_v("\n "+_s(title)+"\n ")]),_v(" "),_c('input',
{directives:[{name:"model",rawName:"v-model",value: 
(course),expression:"course"}],attrs:{"type":"text"},domProps:
{"value": (course)},on:{"keydown":function($event) 
{if(!$event.type.indexOf('key')&&_k($event.keyCode,"enter",13,$event
.key,"Enter" ))return null;return 
addCourse($event)},"input":function($event) 
{if($event.target.composing)return;course=$event.target.value}}}),_v
(" "),_c('button',{on:{"click":addCourse}},[_v("新增课程")]),_v(" "),
(courses.length == 0)?_c('p',[_v("没有任何课程信息")]):_e(),_v(" 
"),_c('ul',_l((courses),function(c){return _c('li',{class:{active:
(selectedCourse === c)},on:{"click":function($event){selectedCourse 
= c}}}, [_v(_s(c))])}),0)])}
})

改写为渲染函数版本试试,

const app = new Vue({
	// 引入上面的render函数
    render(){
    	with(this){return ...}
    }
})

结论 : Vue通过它的编译器将模板编译成渲染函数,在数据发生变化的时候再次执行渲染函数,通过对 比两次执行结果得出要做的dom操作,模板中的神奇魔法得以实现

如果你熟悉虚拟 DOM 并且偏爱 JavaScript 的原始力量,也可以不用模板,直接写渲染 (render) 函数