Index

October 6, 2017

Vue Virtual Template to render function

在Vue2.0中,模板语法会编译成render function。首先来看一下源码中定义的内部render的帮助方法

// core/instance/render.js
  vm._c = (a, b, c, d) => createElement(vm, a, b, c, d, false) // 创建元素

  Vue.prototype._o = markOnce // 仅记一次埋点
  Vue.prototype._n = toNumber // 转为 Number 类型
  Vue.prototype._s = toString // 转为 String 类型
  Vue.prototype._l = renderList // 渲染列表
  Vue.prototype._t = renderSlot // 渲染插槽
  Vue.prototype._q = looseEqual // 比较两个对象是否等值的方法
  Vue.prototype._i = looseIndexOf // 返回某个值的下标
  Vue.prototype._m = renderStatic // 渲染静态资源
  Vue.prototype._f = resolveFilter // 解析 Filter
  Vue.prototype._k = checkKeyCodes // 检查用户自定义的 v-on 属性
  Vue.prototype._b = bindObjectProps // 将 v-bind="object" 的数据绑定到 VNode's data
  Vue.prototype._v = createTextVNode // 生成文本节点
  Vue.prototype._e = createEmptyVNode // 生成空节点
  Vue.prototype._u = resolveScopedSlots // 解析 ScopedSlots

v-if

<div>
  <p v-if="message">
    {{ message }}
  </p>
  <p v-else>
    No message.
  </p>
</div>
// render function
function anonymous() {
  with(this){return _c('div',[(message)?_c('p',[_v(_s(message))]):_c('p',[_v("No message.")])])}
}

v-if被编译成一个三元表达式

v-model

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

{directives:[...],domProps:{...},on:{...} } 将会传入到VNode的data属性中。

staticRenderFns

<div>
  <header>
    <h1>I'm a template!</h1>
  </header>
</div>
// render function
function anonymous() {
  with(this){return _m(0)}
}
//staticRenderFns
_m(0): function anonymous() {
  with(this){return _c('div',[_c('header',[_c('h1',[_v("I'm a template!")])])])}
}

这些与data没有关联,不会发生变化的VNode节点,会单独生成staticRenderFns 函数。与VDOM 中 diff算法优化相关

Vue2.0 源码阅读:模板渲染

Vue源码浅析(三)-render函数