v-if,v-for,v-model的实现原理

npm install vue-template-complier

v-if

let compiler = require('vue-template-compiler');
const ast = compiler.compile('<div v-if="true"></template>');
console.log(ast.render)

控制台输出:

with(this){return (true)?_c('div'):_e()}

解释:
v-if 最终被解释为js语法,可以理解为就是三目运算符

v-for

let compiler = require('vue-template-compiler');
const ast = compiler.compile('<div v-for="i in 3"></div>');
console.log(ast.render)

控制台输出:

with(this){return _l((3),function(i){return _c('div')})}

解释:
v-for和v-if一样被编译为一段js语法

v-model

v-model和input一起使用

let compiler = require('vue-template-compiler');
const ast = compiler.compile('<input v-model="name"></div>');
console.log(ast.render)

控制台输出:

with(this){return _c('input',{directives:[{name:"model",rawName:"v-model",value:(name),expression:"name"}],domProps:{"value":(name)},on:{"input":function($event){if($event.target.composing)return;name=$event.target.value}}})}

解释:
v-model最终被解析成一个指令,不同于前面提到的两个指令v-if和v-for最终解析为js语法;这个指令在运行中会被处理,所以原生input加v-model指令之后,会有一个value属性和input事件,并且内部会处理输入法的问题

v-model和自定义组件一起使用

let compiler = require('vue-template-compiler');
const ast = compiler.compile('<component v-model="name"></component>');
console.log(ast.render)

控制台输出:

with(this){return _c('component',{model:{value:(name),callback:function ($$v) {name=$$v},expression:"name"}})}

解释:
v-mode+自定义组件,本质就是一个input加value的语法糖

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容