UNPKG

reecho

Version:

Reecho 是一款基于依赖收集的MVVM框架,它具有以下特点 - 声明式数据: 基于proxy的依赖收集 - 使用函数定义组件,但组件不会如React一样重复执行造成心智负担 - 读写分离,读取状态和更改状态统一使用函数,避免vue3的ref一样有时需要`xxx.value`有时不需要的不一致性 - 使用TS编写,类型友好

37 lines (32 loc) 1.02 kB
import { getCurrentInstance } from "./components"; import { isFunction } from "../shared/index"; export interface InjectionKey<T> extends Symbol {} export function provide<T>(key: InjectionKey<T> | string | number, value: T) { const currentInstance = getCurrentInstance(); if (!currentInstance) { return; } let { provides } = currentInstance; const parentProvides = currentInstance.parent?.provides; if (provides === parentProvides) { provides = currentInstance.provides = Object.create(parentProvides); } provides[key as any] = value; } export function inject<T = any>( key: InjectionKey<T> | string, defaultValue?: T ): T { const currentInstance = getCurrentInstance(); if (currentInstance) { const provides = currentInstance.parent?.provides; if (provides && (key as string) in provides) { return provides[key as string]; } else if (defaultValue) { if (isFunction(defaultValue)) { return defaultValue(); } return defaultValue; } } }