<!-- 场景设置 -->
<!-- 父组件 -->
<div>
<test>
<template slot-scope="slotProps">
我是放在组件的slot: {{slotProps}}
</template>
</test>
</div>
<!-- 子组件 -->
<main>
我在子组件里面
<slot :child="child"></slot>
</main>
data() {
return {child: 111}
}
父组件会被解析成如下的渲染函数
with(this) {
return _c('div', {},
[_c('test', {
scopedSlots: _u([{
key: "default",
fn: function(slotProps) {
return [ "我是放在组件的 slot :"+slotProps ]
}
}])
})],
1)
}
其中_u
是resolveScopedSlots, Vue会给每个实例都注册一个_u
方法
function resolveScopedSlots(fns, res) {
res = res || {};
for (var i = 0; i < fns.length; i++) {
res[fns[i].key] = fns[i].fn;
}
return res
}
将上面渲染函数传递给_u
的参数通过resolveScopedSlots转化为对象就是
{
default: function(slotProps) {
return ["我是放在组件的 slot :" + slotProps]
}
}
将作用域插槽包装成函数,其目的就是为了改变插槽内容访问变量的作用域,通过参数传递的形式,让插槽的变量,在解析时,先访问函数变量。
作用域插槽的解析流程:
- 插槽函数保存到外壳节点
- 插槽函数另存为,test组件会创建自身实例
// 这个函数作用是,执行渲染函数,得到组件节点
Vue.prototype._render = function() {
var vm = this;
var ref = vm.$options;
// _parentVnode 就是外壳节点
var _parentVnode = ref._parentVnode;
if (_parentVnode) {
vm.$scopedSlots = _parentVnode.data.scopedSlots || {};
}
...省略N多执行渲染函数的代码
vm.$vnode = _parentVnode;
return vnode
};
- 子组件解析
with(this) {
return _c('main', [
'我在子组件里面',
_t('default', null, {
child: child
})
]);
}
_t
是renderSlot, 这个方法会兼容普通的slot和作用域slot
function renderSlot(name, fallback, props) {
// 看了上面,所以可以从实例上获取$scopedSlots
var scopedSlotFn = this.$scopedSlots[name];
var nodes;
if (scopedSlotFn) {
props = props || {};
// 开始执行插槽函数
nodes = scopedSlotFn(props);
}
return nodes
}