以下代码中的h是如何变成vm.$createElement的?
new V({
el: '#app',
render(h) {
return h(App)
}
})
简化Vue执行render函数的流程如下:
// 假设App是引入的组件
const App = {
name: 'this is a App!'
};
// 定义构造函数
function V(options) {
this._init(options)
}
// 定义原型初始化方法
V.prototype._init = function (options) {
const vm = this;
vm.$options = options;
vm.$createElement = (a, b, c, d) => {
return {
name: 'this is a Vnode!'
}
}
// render就是实例化时传入的render(h) {return h(App)}
const { render } = vm.$options;
// vm是执行主体,而vm.$createElement是render执行时传入的唯一一个实参,即h就是vm.$createElement
const vNode = render.call(vm, vm.$createElement);
console.log(vNode);
}
// 实例化V函数
new V({
el: '#app',
render(h) {
return h(App)
}
})
在Vue中的真实执行位置
Vue.prototype._render = function() {
try {
vnode = render.call(vm._renderProxy, vm.$createElement)
} catch (e) {
...
} finally {
...
}
}
总结:render(h) { return h(App) }作为new Vue()的参数,在获取Vnode执行过程中被Vue实例vm调用,传入唯一的实参vm.$createElement,此时h就等价于vm.createElement。