vue3 provide和 reject

//APP.vue  父组件传递值
// setup(){
//     let num = ref(1)
//     provide('num',num)
// }

//子组件接收值
// setup(){
//     var result = inject('num')
//     console.log(result)
// }

let currentInstance = null;
function provide(key, value) {
    if (!currentInstance) {
        {
            warn$1(`provide() can only be used inside setup().`);
        }
    }
    else {
        let provides = currentInstance.provides;
        // by default an instance inherits its parent's provides object
        // but when it needs to provide values of its own, it creates its
        // own provides object using parent provides object as prototype.
        // this way in `inject` we can simply look up injections from direct
        // parent and let the prototype chain do the work.
        //默认情况下,实例继承其父对象
        //但当它需要提供自己的价值时,它就会创造自己的价值
        //own使用父对象作为原型提供对象。
        //通过这种方式,在'inject'中,我们可以简单地从direct中查找注入
        //创建父对象并让原型链完成工作。
        const parentProvides = currentInstance.parent && currentInstance.parent.provides;
        if (parentProvides === provides) {
            provides = currentInstance.provides = Object.create(parentProvides);
        }
        // TS doesn't allow symbol as index type
        //TS不允许将符号作为索引类型
        provides[key] = value;
    }
}

function inject(key, defaultValue, treatDefaultAsFactory = false) {
    // fallback to `currentRenderingInstance` so that this can be called in
    // a functional component
    //回退到'currentRenderingInstance',以便可以在中调用它
    //功能部件
    const instance = currentInstance || currentRenderingInstance;
    if (instance) {
        // #2400
        // to support `app.use` plugins,
        // fallback to appContext's `provides` if the intance is at root
        //要支持'app.use'插件,
        //如果intance位于根目录下,则回退到appContext的'provides'
        const provides = instance.parent == null
            ? instance.vnode.appContext && instance.vnode.appContext.provides
            : instance.parent.provides;
        if (provides && key in provides) {
            // TS doesn't allow symbol as index type
            return provides[key];
        }
        else if (arguments.length > 1) {
            return treatDefaultAsFactory && isFunction(defaultValue)
                ? defaultValue.call(instance.proxy)
                : defaultValue;
        }
        else {
            warn$1(`injection "${String(key)}" not found.`);
        }
    }
    else {
        warn$1(`inject() can only be used inside setup() or functional components.`);
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值