20-实现getCurrentInstance

800 阅读1分钟

思考

vue3中的getCurrentInstance api是 Composition API独有的语法糖,用来获取当前组件的实例

  1. 只有Composition Api有
  2. 每个组件都是独立的

根据以上两个特点实现

实现

component.ts

function setupStatefulComponent(instance, container) {
  // other code
  
  if (setup) {
    /**
     * 1. setup接收props、context
     * 2. 设置 currentInstance
     * 2. 执行setup
     */

    setCurrentInstance(instance);
    const setupResult = setup(shallowReadonly(instance.props), {
      emit: instance.emit,
    });
    /** 清除currentInstance
     * 1. 每个组件的getCurrentInstance都是独立的
     * 2. 每次初始化完setup,必须把currentInstance清空,避免影响其他
     * 3. getCurrentInstance 只是 Composition API 的语法糖
     */
    setCurrentInstance(null);
    handleSetupResult(instance, setupResult);
  }
}

export function getCurrentInstance() {
  return currentInstance;
}

function setCurrentInstance(instance) {
  currentInstance = instance;
}