//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.`);
}
}
vue3 provide和 reject
最新推荐文章于 2024-05-20 16:40:30 发布