- with语法
- vue template complier 将编译为render函数
- 执行render函数生成vnode
模版编译前置知识-with语法
- 改变 { } 内自由变量的查找规则, 当作obj属性来查找
- 如果找不到匹配的obj属性, 就会报错
- with要慎用, 他打破了作用域规则, 易读性变差
模版, 不是html, 有指令、插值、js表达式, 能实现判断、循环。html 是标签语言, 只有JS才能实现判断、循环。因此, 模版语言一定是转换为某种JS代码,即编译模版。
- 模版编译为render函数, 执行render函数返回vnode
- 基于vnode再执行patch和diff
- 使用webpack vue-loader, 会在开发环境下编译模版
vue模版被编译后的内容
1. 插值const template = `<p>{{message}}</p>`with(this){return createElement('p',[createTextVNode(toString(message))])}2. 表达式const template = `<p>{{flag ? message : 'no message found'}}</p>`with(this){return _c('p',[_v(_s(flag ? message : 'no message found'))])}3. 属性和动态属性const template = `<div id="div1" class="container"><img :src="imgUrl"/></div>`with(this){return _c('div',{staticClass:"container",attrs:{"id":"div1"}},[ _c('img',{attrs:{"src":imgUrl}})] )}4. 条件const template = `<div><p v-if="flag === 'a'">A</p><p v-else>B</p></div>`with(this){return _c('div',[(flag === 'a') ? _c('p',[_v("A")]) : _c('p',[_v("B")]) ] )}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. 事件const template = `<button @click="clickHandler">submit</button>`with(this){return _c('button',{on:{"click":clickHandler}}, [_v("submit")] )}7. v-modelconst template = `<input type="text" v-model="name">`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}}})}
render代替template
复杂情况下, 不能template时, 可以考虑使用render
React中一直使用render,没有template
