Vue作用域slot原理分析

<!-- 场景设置 -->
<!-- 父组件 -->
<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]
    }
}

将作用域插槽包装成函数,其目的就是为了改变插槽内容访问变量的作用域,通过参数传递的形式,让插槽的变量,在解析时,先访问函数变量。

作用域插槽的解析流程:

  1. 插槽函数保存到外壳节点
  2. 插槽函数另存为,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
};
  1. 子组件解析
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
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值