vue的模板编译

模板不是html,有指令、插值、js表达式,能实现判断、循环。
html是标签语言,只有js才能实现判断、循环(图灵完备)
因此,模板一定是转换为某种js代码,即模板编译。

1、准备

  1. 使用npm init -y 创建一个空项目
  2. npm install vue-template-compiler下载vue模板编译插件
  3. 创建一个index.js文件,在里面引入上述插件
  4. 写一个模板字符串,如
const template=`<p class='box con' id='dd' style='color:"#333"' :age='23'>{{message}}<span>234</span></p>`
  1. 编译模板字符串
const res=compiler.compile(template)
console.log(res.render)
  1. 在终端执行node index查看打印结果

2、vue各函数

1、_c

createElement,就是h函数
第一个参数是标签,后面的参数是一个数组(子元素)

2、_v

createTextVNode

3、_s

toString

4、_l

renderList,渲染列表

3、各模板字符串编译的结果

1、简单的模板

const template=`<p>{{message}}</p>`

编译后返回

with(this){return _c('p',[_v(_s(message))])}

this就是当前的vue实例。
_c函数执行后,返回vnode

2、表达式

const template=`<p>{{flag?message:'no message found'}}</p>`
with(this){return _c('p',[_v(_s(flag?message:'no message found'))])}

在_s函数中传入了三元表达式,它会先执行然后传入_s函数去执行。

3、属性和动态属性

const template=`<div id='div1' class='container'>
<img :src='url'/>
</div>`
with(this){return 
_c('div',{staticClass:"container",attrs:{"id":"div1"}},
[_c('img',{attrs:{"src":url}})])}

_c函数的第二项参数,是一个对象,是它的属性
动态属性放在attrs属性中

4、条件

const template=`<div>
<p v-if="flag==='a'">name</p>
<p v-else>age</p>
</div>`
with(this){return _c('div',[(flag==='a')?_c('p',[_v("name")]):_c('p',[_v("age")])])}

子元素数组中,有一个三元表达式

5、循环

const template=`<ul>
<li v-for="item in list" :key="item.id">{{item.title}}</li>
</ul>`
with(this){return _c('ul',_l((list),function(item){return _c('li',{key:item.id},[_v(_s(item.title))])}),0)}

6、事件

`<button @click='handler'>submit</button>`
with(this){return _c('button',{on:{"click":handler}},[_v("submit")])}

_c函数的第二个参数中有一个on属性,里面有事件

7、v-model

const template=`<input type='text' v-model='name'></input>`
with(this){return _c('input',
{directives:[{name:"model",rawName:"v-model",value:(name),expression:"name"}],
attrs:{"type":"text"},
domProps:{"value":(name)},
on{"input":function($event{if($event.target.composing)return;name=$event.target.value}}})}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值