If help big brother, please give little brother a zan ha!
Provides a source of
Each component is instantiated using the parent component’s provides if there is one, {} if there is none.
const instance = {
type: vnode.type,
vnode,
next: null.props: {},
parent,
provides: parent ? parent.provides : {},
proxy: null.isMounted: false.attrs: {},
slots: {},
ctx: {},
setupState: {},
emit: () = >{}};Copy the code
Provides the source code
Void 0 = undefined; void 0 = undefined; If an instance has a parent component, its provides are equal to parent. Provides.
- When parentProvides === provides, place the parentProvides in the prototype chain. If a component accesses a key, it preferentially accesses the key set by the parent component. If it cannot find the key, it continues to search for the key.
- provides[key] = value; Set your own provide.
function provide(key, value) {
var _a;
const currentInstance = getCurrentInstance();
if (currentInstance) {
let { provides } = currentInstance;
const parentProvides = (_a = currentInstance.parent) === null || _a === void 0 ? void 0 : _a.provides;
if (parentProvides === provides) {
provides = currentInstance.provides = Object.create(parentProvides); } provides[key] = value; }}Copy the code
Is the above analysis correct? Let’s verify that the multiple nested components are set to provide, and then print an instance of the deepest child component.
Provides is indeed a multilayer prototype chain, you can go to verify.
Inject the source code
- Now if I look for the key on the prototype chain, and I go in, it will go through the original chain. If found, return provides[key].
- DefaultValue is a function that returns the result, not a function that directly returns defaultValue.
- If the prototype chain is not found and the default value is not set, return will not return, which will default to return undefined.
function inject(key, defaultValue) {
var _a;
const currentInstance = getCurrentInstance();
if (currentInstance) {
const provides = (_a = currentInstance.parent) === null || _a === void 0 ? void 0 : _a.provides;
if (key in provides) {
return provides[key];
} else if (defaultValue) {
if (typeof defaultValue === "function") {
return defaultValue();
}
returndefaultValue; }}}Copy the code
conclusion
This part of the source code is very simple, we try to read it.