美文网首页程序员
v-if,v-for,v-model的实现原理

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

作者: 墨子柚 | 来源:发表于2020-06-07 11:36 被阅读0次

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的语法糖

相关文章

  • 基本指令

    基本指令: 插值、v-bind、v-if、v-for、v-on、v-model

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

    npm install vue-template-complier v-if 控制台输出: 解释:v-if 最终被...

  • vue.js

    v-if v-else-if v-else v-for v-on 绑定事件 , 简写 @ v-model 数据双向...

  • vue指令

    指令 v-for v-if v-show v-model 在表单 元素上创建双向数据绑定 v-...

  • VUE复习 组件通信、vuex

    一、 常用指令:v-for,v-if,v-else,v-model二、 绑定事件:@事件名 例如:@clic...

  • vue基础概念

    1、v-model(绑定数据)2、v-for(循环)3、v-on(绑定事件)4、$index(索引)5、v-if(...

  • 第一天--vuejs的学习

    vue的模版语法: 模块渲染声明式渲染;v-bind; v-model; v-on; v-if; v-for; v...

  • 第四、五周问题集锦

    任务一:Vue使用 版本:Vue1知识点:v-model、v-for、v-if ... v-else ...、v-...

  • 12.12 默写

    1.指令 v-text v-show v-if v-else v-for v-on v-bind v-model ...

  • Vue2.0系列(二、vue基本指令)

    今天主要vue的使用v-if,v-for,v-model,数据双向绑定,处理表单和选框,class与style的常...

网友评论

    本文标题:v-if,v-for,v-model的实现原理

    本文链接:https://www.haomeiwen.com/subject/pgtctktx.html