From 5828f2441f7ece8336e8682a5ab8a285a1e8e77c Mon Sep 17 00:00:00 2001 From: Evan You Date: Sun, 1 Dec 2024 17:00:38 +0800 Subject: [PATCH] perf: use class for SetupContext --- packages/runtime-vapor/src/component.ts | 76 ++++++++++++------------- 1 file changed, 37 insertions(+), 39 deletions(-) diff --git a/packages/runtime-vapor/src/component.ts b/packages/runtime-vapor/src/component.ts index 1cdf4f334..89f8ccc88 100644 --- a/packages/runtime-vapor/src/component.ts +++ b/packages/runtime-vapor/src/component.ts @@ -34,42 +34,25 @@ export type FunctionalComponent = SetupFn & displayName?: string } -export type SetupContext = E extends any - ? { - attrs: Data - emit: EmitFn - expose: (exposed?: Record) => void - slots: Readonly +export class SetupContext { + attrs: Data + emit: EmitFn + slots: Readonly + expose: (exposed?: Record) => void + + constructor(instance: ComponentInternalInstance) { + this.attrs = instance.attrs + this.emit = instance.emit as EmitFn + this.slots = instance.slots + this.expose = (exposed = {}) => { + instance.exposed = exposed } - : never + } +} export function createSetupContext( instance: ComponentInternalInstance, ): SetupContext { - const expose: SetupContext['expose'] = exposed => { - if (__DEV__) { - if (instance.exposed) { - warn(`expose() should be called only once per setup().`) - } - if (exposed != null) { - let exposedType: string = typeof exposed - if (exposedType === 'object') { - if (isArray(exposed)) { - exposedType = 'array' - } else if (isRef(exposed)) { - exposedType = 'ref' - } - } - if (exposedType !== 'object') { - warn( - `expose() should be passed a plain object, received ${exposedType}.`, - ) - } - } - } - instance.exposed = exposed || {} - } - if (__DEV__) { // We use getters in dev in case libs like test-utils overwrite instance // properties (overwrites should not be done in prod) @@ -83,15 +66,30 @@ export function createSetupContext( get emit() { return (event: string, ...args: any[]) => instance.emit(event, ...args) }, - expose, - }) + expose: (exposed?: Record) => { + if (instance.exposed) { + warn(`expose() should be called only once per setup().`) + } + if (exposed != null) { + let exposedType: string = typeof exposed + if (exposedType === 'object') { + if (isArray(exposed)) { + exposedType = 'array' + } else if (isRef(exposed)) { + exposedType = 'ref' + } + } + if (exposedType !== 'object') { + warn( + `expose() should be passed a plain object, received ${exposedType}.`, + ) + } + } + instance.exposed = exposed || {} + }, + }) as SetupContext } else { - return { - attrs: instance.attrs, - emit: instance.emit, - slots: instance.slots, - expose, - } + return new SetupContext(instance) } }