模板不是html,有指令、插值、js表达式,能实现判断、循环。
html是标签语言,只有js才能实现判断、循环(图灵完备)
因此,模板一定是转换为某种js代码,即模板编译。
1、准备
- 使用npm init -y 创建一个空项目
- npm install vue-template-compiler下载vue模板编译插件
- 创建一个index.js文件,在里面引入上述插件
- 写一个模板字符串,如
const template=`<p class='box con' id='dd' style='color:"#333"' :age='23'>{{message}}<span>234</span></p>`
- 编译模板字符串
const res=compiler.compile(template)
console.log(res.render)
- 在终端执行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}}})}