-
-
Notifications
You must be signed in to change notification settings - Fork 8.4k
/
componentOptions.ts
946 lines (884 loc) · 22.7 KB
/
componentOptions.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
import {
ComponentInternalInstance,
Data,
SetupContext,
ComponentInternalOptions,
Component,
ConcreteComponent,
InternalRenderFunction,
LifecycleHooks
} from './component'
import {
isFunction,
extend,
isString,
isObject,
isArray,
EMPTY_OBJ,
NOOP,
hasOwn,
isPromise
} from '@vue/shared'
import { computed } from './apiComputed'
import { watch, WatchOptions, WatchCallback } from './apiWatch'
import { provide, inject } from './apiInject'
import {
onBeforeMount,
onMounted,
onBeforeUpdate,
onUpdated,
onErrorCaptured,
onRenderTracked,
onBeforeUnmount,
onUnmounted,
onActivated,
onDeactivated,
onRenderTriggered,
DebuggerHook,
ErrorCapturedHook
} from './apiLifecycle'
import {
reactive,
ComputedGetter,
WritableComputedOptions,
toRaw,
proxyRefs,
toRef
} from '@vue/reactivity'
import {
ComponentObjectPropsOptions,
ExtractPropTypes,
ExtractDefaultPropTypes
} from './componentProps'
import { EmitsOptions } from './componentEmits'
import { Directive } from './directives'
import {
CreateComponentPublicInstance,
ComponentPublicInstance
} from './componentPublicInstance'
import { warn } from './warning'
import { VNodeChild } from './vnode'
import { callWithAsyncErrorHandling } from './errorHandling'
/**
* Interface for declaring custom options.
*
* @example
* ```ts
* declare module '@vue/runtime-core' {
* interface ComponentCustomOptions {
* beforeRouteUpdate?(
* to: Route,
* from: Route,
* next: () => void
* ): void
* }
* }
* ```
*/
export interface ComponentCustomOptions {}
export type RenderFunction = () => VNodeChild
export interface ComponentOptionsBase<
Props,
RawBindings,
D,
C extends ComputedOptions,
M extends MethodOptions,
Mixin extends ComponentOptionsMixin,
Extends extends ComponentOptionsMixin,
E extends EmitsOptions,
EE extends string = string,
Defaults = {}
>
extends LegacyOptions<Props, D, C, M, Mixin, Extends>,
ComponentInternalOptions,
ComponentCustomOptions {
setup?: (
this: void,
props: Props,
ctx: SetupContext<E, Props>
) => Promise<RawBindings> | RawBindings | RenderFunction | void
name?: string
template?: string | object // can be a direct DOM node
// Note: we are intentionally using the signature-less `Function` type here
// since any type with signature will cause the whole inference to fail when
// the return expression contains reference to `this`.
// Luckily `render()` doesn't need any arguments nor does it care about return
// type.
render?: Function
components?: Record<string, Component>
directives?: Record<string, Directive>
inheritAttrs?: boolean
emits?: (E | EE[]) & ThisType<void>
// TODO infer public instance type based on exposed keys
expose?: string[]
serverPrefetch?(): Promise<any>
// Internal ------------------------------------------------------------------
/**
* SSR only. This is produced by compiler-ssr and attached in compiler-sfc
* not user facing, so the typing is lax and for test only.
* @internal
*/
ssrRender?: (
ctx: any,
push: (item: any) => void,
parentInstance: ComponentInternalInstance,
attrs: Data | undefined,
// for compiler-optimized bindings
$props: ComponentInternalInstance['props'],
$setup: ComponentInternalInstance['setupState'],
$data: ComponentInternalInstance['data'],
$options: ComponentInternalInstance['ctx']
) => void
/**
* Only generated by compiler-sfc to mark a ssr render function inlined and
* returned from setup()
* @internal
*/
__ssrInlineRender?: boolean
/**
* marker for AsyncComponentWrapper
* @internal
*/
__asyncLoader?: () => Promise<ConcreteComponent>
/**
* cache for merged $options
* @internal
*/
__merged?: ComponentOptions
// Type differentiators ------------------------------------------------------
// Note these are internal but need to be exposed in d.ts for type inference
// to work!
// type-only differentiator to separate OptionWithoutProps from a constructor
// type returned by defineComponent() or FunctionalComponent
call?: (this: unknown, ...args: unknown[]) => never
// type-only differentiators for built-in Vnode types
__isFragment?: never
__isTeleport?: never
__isSuspense?: never
__defaults?: Defaults
}
export type ComponentOptionsWithoutProps<
Props = {},
RawBindings = {},
D = {},
C extends ComputedOptions = {},
M extends MethodOptions = {},
Mixin extends ComponentOptionsMixin = ComponentOptionsMixin,
Extends extends ComponentOptionsMixin = ComponentOptionsMixin,
E extends EmitsOptions = EmitsOptions,
EE extends string = string
> = ComponentOptionsBase<
Props,
RawBindings,
D,
C,
M,
Mixin,
Extends,
E,
EE,
{}
> & {
props?: undefined
} & ThisType<
CreateComponentPublicInstance<{}, RawBindings, D, C, M, Mixin, Extends, E>
>
export type ComponentOptionsWithArrayProps<
PropNames extends string = string,
RawBindings = {},
D = {},
C extends ComputedOptions = {},
M extends MethodOptions = {},
Mixin extends ComponentOptionsMixin = ComponentOptionsMixin,
Extends extends ComponentOptionsMixin = ComponentOptionsMixin,
E extends EmitsOptions = EmitsOptions,
EE extends string = string,
Props = Readonly<{ [key in PropNames]?: any }>
> = ComponentOptionsBase<
Props,
RawBindings,
D,
C,
M,
Mixin,
Extends,
E,
EE,
{}
> & {
props: PropNames[]
} & ThisType<
CreateComponentPublicInstance<
Props,
RawBindings,
D,
C,
M,
Mixin,
Extends,
E
>
>
export type ComponentOptionsWithObjectProps<
PropsOptions = ComponentObjectPropsOptions,
RawBindings = {},
D = {},
C extends ComputedOptions = {},
M extends MethodOptions = {},
Mixin extends ComponentOptionsMixin = ComponentOptionsMixin,
Extends extends ComponentOptionsMixin = ComponentOptionsMixin,
E extends EmitsOptions = EmitsOptions,
EE extends string = string,
Props = Readonly<ExtractPropTypes<PropsOptions>>,
Defaults = ExtractDefaultPropTypes<PropsOptions>
> = ComponentOptionsBase<
Props,
RawBindings,
D,
C,
M,
Mixin,
Extends,
E,
EE,
Defaults
> & {
props: PropsOptions & ThisType<void>
} & ThisType<
CreateComponentPublicInstance<
Props,
RawBindings,
D,
C,
M,
Mixin,
Extends,
E,
Props,
Defaults,
false
>
>
export type ComponentOptions<
Props = {},
RawBindings = any,
D = any,
C extends ComputedOptions = any,
M extends MethodOptions = any,
Mixin extends ComponentOptionsMixin = any,
Extends extends ComponentOptionsMixin = any,
E extends EmitsOptions = any
> = ComponentOptionsBase<Props, RawBindings, D, C, M, Mixin, Extends, E> &
ThisType<
CreateComponentPublicInstance<
{},
RawBindings,
D,
C,
M,
Mixin,
Extends,
E,
Readonly<Props>
>
>
export type ComponentOptionsMixin = ComponentOptionsBase<
any,
any,
any,
any,
any,
any,
any,
any,
any,
any
>
export type ComputedOptions = Record<
string,
ComputedGetter<any> | WritableComputedOptions<any>
>
export interface MethodOptions {
[key: string]: Function
}
export type ExtractComputedReturns<T extends any> = {
[key in keyof T]: T[key] extends { get: (...args: any[]) => infer TReturn }
? TReturn
: T[key] extends (...args: any[]) => infer TReturn ? TReturn : never
}
type WatchOptionItem =
| string
| WatchCallback
| { handler: WatchCallback | string } & WatchOptions
type ComponentWatchOptionItem = WatchOptionItem | WatchOptionItem[]
type ComponentWatchOptions = Record<string, ComponentWatchOptionItem>
type ComponentInjectOptions =
| string[]
| Record<
string | symbol,
string | symbol | { from?: string | symbol; default?: unknown }
>
interface LegacyOptions<
Props,
D,
C extends ComputedOptions,
M extends MethodOptions,
Mixin extends ComponentOptionsMixin,
Extends extends ComponentOptionsMixin
> {
// allow any custom options
[key: string]: any
// state
// Limitation: we cannot expose RawBindings on the `this` context for data
// since that leads to some sort of circular inference and breaks ThisType
// for the entire component.
data?: (
this: CreateComponentPublicInstance<Props>,
vm: CreateComponentPublicInstance<Props>
) => D
computed?: C
methods?: M
watch?: ComponentWatchOptions
provide?: Data | Function
inject?: ComponentInjectOptions
// composition
mixins?: Mixin[]
extends?: Extends
// lifecycle
beforeCreate?(): void
created?(): void
beforeMount?(): void
mounted?(): void
beforeUpdate?(): void
updated?(): void
activated?(): void
deactivated?(): void
/** @deprecated use `beforeUnmount` instead */
beforeDestroy?(): void
beforeUnmount?(): void
/** @deprecated use `unmounted` instead */
destroyed?(): void
unmounted?(): void
renderTracked?: DebuggerHook
renderTriggered?: DebuggerHook
errorCaptured?: ErrorCapturedHook
// runtime compile only
delimiters?: [string, string]
}
export type OptionTypesKeys = 'P' | 'B' | 'D' | 'C' | 'M' | 'Defaults'
export type OptionTypesType<
P = {},
B = {},
D = {},
C extends ComputedOptions = {},
M extends MethodOptions = {},
Defaults = {}
> = {
P: P
B: B
D: D
C: C
M: M
Defaults: Defaults
}
const enum OptionTypes {
PROPS = 'Props',
DATA = 'Data',
COMPUTED = 'Computed',
METHODS = 'Methods',
INJECT = 'Inject'
}
function createDuplicateChecker() {
const cache = Object.create(null)
return (type: OptionTypes, key: string) => {
if (cache[key]) {
warn(`${type} property "${key}" is already defined in ${cache[key]}.`)
} else {
cache[key] = type
}
}
}
type DataFn = (vm: ComponentPublicInstance) => any
export let isInBeforeCreate = false
export function applyOptions(
instance: ComponentInternalInstance,
options: ComponentOptions,
deferredData: DataFn[] = [],
deferredWatch: ComponentWatchOptions[] = [],
deferredProvide: (Data | Function)[] = [],
asMixin: boolean = false
) {
const {
// composition
mixins,
extends: extendsOptions,
// state
data: dataOptions,
computed: computedOptions,
methods,
watch: watchOptions,
provide: provideOptions,
inject: injectOptions,
// assets
components,
directives,
// lifecycle
beforeMount,
mounted,
beforeUpdate,
updated,
activated,
deactivated,
beforeDestroy,
beforeUnmount,
destroyed,
unmounted,
render,
renderTracked,
renderTriggered,
errorCaptured,
// public API
expose
} = options
const publicThis = instance.proxy!
const ctx = instance.ctx
const globalMixins = instance.appContext.mixins
if (asMixin && render && instance.render === NOOP) {
instance.render = render as InternalRenderFunction
}
// applyOptions is called non-as-mixin once per instance
if (!asMixin) {
isInBeforeCreate = true
callSyncHook(
'beforeCreate',
LifecycleHooks.BEFORE_CREATE,
options,
instance,
globalMixins
)
isInBeforeCreate = false
// global mixins are applied first
applyMixins(
instance,
globalMixins,
deferredData,
deferredWatch,
deferredProvide
)
}
// extending a base component...
if (extendsOptions) {
applyOptions(
instance,
extendsOptions,
deferredData,
deferredWatch,
deferredProvide,
true
)
}
// local mixins
if (mixins) {
applyMixins(instance, mixins, deferredData, deferredWatch, deferredProvide)
}
const checkDuplicateProperties = __DEV__ ? createDuplicateChecker() : null
if (__DEV__) {
const [propsOptions] = instance.propsOptions
if (propsOptions) {
for (const key in propsOptions) {
checkDuplicateProperties!(OptionTypes.PROPS, key)
}
}
}
// options initialization order (to be consistent with Vue 2):
// - props (already done outside of this function)
// - inject
// - methods
// - data (deferred since it relies on `this` access)
// - computed
// - watch (deferred since it relies on `this` access)
if (injectOptions) {
if (isArray(injectOptions)) {
for (let i = 0; i < injectOptions.length; i++) {
const key = injectOptions[i]
ctx[key] = inject(key)
if (__DEV__) {
checkDuplicateProperties!(OptionTypes.INJECT, key)
}
}
} else {
for (const key in injectOptions) {
const opt = injectOptions[key]
if (isObject(opt)) {
ctx[key] = inject(
opt.from || key,
opt.default,
true /* treat default function as factory */
)
} else {
ctx[key] = inject(opt)
}
if (__DEV__) {
checkDuplicateProperties!(OptionTypes.INJECT, key)
}
}
}
}
if (methods) {
for (const key in methods) {
const methodHandler = (methods as MethodOptions)[key]
if (isFunction(methodHandler)) {
ctx[key] = methodHandler.bind(publicThis)
if (__DEV__) {
checkDuplicateProperties!(OptionTypes.METHODS, key)
}
} else if (__DEV__) {
warn(
`Method "${key}" has type "${typeof methodHandler}" in the component definition. ` +
`Did you reference the function correctly?`
)
}
}
}
if (!asMixin) {
if (deferredData.length) {
deferredData.forEach(dataFn => resolveData(instance, dataFn, publicThis))
}
if (dataOptions) {
resolveData(instance, dataOptions, publicThis)
}
if (__DEV__) {
const rawData = toRaw(instance.data)
for (const key in rawData) {
checkDuplicateProperties!(OptionTypes.DATA, key)
// expose data on ctx during dev
if (key[0] !== '$' && key[0] !== '_') {
Object.defineProperty(ctx, key, {
configurable: true,
enumerable: true,
get: () => rawData[key],
set: NOOP
})
}
}
}
} else if (dataOptions) {
deferredData.push(dataOptions as DataFn)
}
if (computedOptions) {
for (const key in computedOptions) {
const opt = (computedOptions as ComputedOptions)[key]
const get = isFunction(opt)
? opt.bind(publicThis, publicThis)
: isFunction(opt.get)
? opt.get.bind(publicThis, publicThis)
: NOOP
if (__DEV__ && get === NOOP) {
warn(`Computed property "${key}" has no getter.`)
}
const set =
!isFunction(opt) && isFunction(opt.set)
? opt.set.bind(publicThis)
: __DEV__
? () => {
warn(
`Write operation failed: computed property "${key}" is readonly.`
)
}
: NOOP
const c = computed({
get,
set
})
Object.defineProperty(ctx, key, {
enumerable: true,
configurable: true,
get: () => c.value,
set: v => (c.value = v)
})
if (__DEV__) {
checkDuplicateProperties!(OptionTypes.COMPUTED, key)
}
}
}
if (watchOptions) {
deferredWatch.push(watchOptions)
}
if (!asMixin && deferredWatch.length) {
deferredWatch.forEach(watchOptions => {
for (const key in watchOptions) {
createWatcher(watchOptions[key], ctx, publicThis, key)
}
})
}
if (provideOptions) {
deferredProvide.push(provideOptions)
}
if (!asMixin && deferredProvide.length) {
deferredProvide.forEach(provideOptions => {
const provides = isFunction(provideOptions)
? provideOptions.call(publicThis)
: provideOptions
for (const key in provides) {
provide(key, provides[key])
}
})
}
// asset options.
// To reduce memory usage, only components with mixins or extends will have
// resolved asset registry attached to instance.
if (asMixin) {
if (components) {
extend(
instance.components ||
(instance.components = extend(
{},
(instance.type as ComponentOptions).components
) as Record<string, ConcreteComponent>),
components
)
}
if (directives) {
extend(
instance.directives ||
(instance.directives = extend(
{},
(instance.type as ComponentOptions).directives
)),
directives
)
}
}
// lifecycle options
if (!asMixin) {
callSyncHook(
'created',
LifecycleHooks.CREATED,
options,
instance,
globalMixins
)
}
if (beforeMount) {
onBeforeMount(beforeMount.bind(publicThis))
}
if (mounted) {
onMounted(mounted.bind(publicThis))
}
if (beforeUpdate) {
onBeforeUpdate(beforeUpdate.bind(publicThis))
}
if (updated) {
onUpdated(updated.bind(publicThis))
}
if (activated) {
onActivated(activated.bind(publicThis))
}
if (deactivated) {
onDeactivated(deactivated.bind(publicThis))
}
if (errorCaptured) {
onErrorCaptured(errorCaptured.bind(publicThis))
}
if (renderTracked) {
onRenderTracked(renderTracked.bind(publicThis))
}
if (renderTriggered) {
onRenderTriggered(renderTriggered.bind(publicThis))
}
if (__DEV__ && beforeDestroy) {
warn(`\`beforeDestroy\` has been renamed to \`beforeUnmount\`.`)
}
if (beforeUnmount) {
onBeforeUnmount(beforeUnmount.bind(publicThis))
}
if (__DEV__ && destroyed) {
warn(`\`destroyed\` has been renamed to \`unmounted\`.`)
}
if (unmounted) {
onUnmounted(unmounted.bind(publicThis))
}
if (isArray(expose)) {
if (!asMixin) {
if (expose.length) {
const exposed = instance.exposed || (instance.exposed = proxyRefs({}))
expose.forEach(key => {
exposed[key] = toRef(publicThis, key as any)
})
} else if (!instance.exposed) {
instance.exposed = EMPTY_OBJ
}
} else if (__DEV__) {
warn(`The \`expose\` option is ignored when used in mixins.`)
}
}
}
function callSyncHook(
name: 'beforeCreate' | 'created',
type: LifecycleHooks,
options: ComponentOptions,
instance: ComponentInternalInstance,
globalMixins: ComponentOptions[]
) {
callHookFromMixins(name, type, globalMixins, instance)
const { extends: base, mixins } = options
if (base) {
callHookFromExtends(name, type, base, instance)
}
if (mixins) {
callHookFromMixins(name, type, mixins, instance)
}
const selfHook = options[name]
if (selfHook) {
callWithAsyncErrorHandling(selfHook.bind(instance.proxy!), instance, type)
}
}
function callHookFromExtends(
name: 'beforeCreate' | 'created',
type: LifecycleHooks,
base: ComponentOptions,
instance: ComponentInternalInstance
) {
if (base.extends) {
callHookFromExtends(name, type, base.extends, instance)
}
const baseHook = base[name]
if (baseHook) {
callWithAsyncErrorHandling(baseHook.bind(instance.proxy!), instance, type)
}
}
function callHookFromMixins(
name: 'beforeCreate' | 'created',
type: LifecycleHooks,
mixins: ComponentOptions[],
instance: ComponentInternalInstance
) {
for (let i = 0; i < mixins.length; i++) {
const chainedMixins = mixins[i].mixins
if (chainedMixins) {
callHookFromMixins(name, type, chainedMixins, instance)
}
const fn = mixins[i][name]
if (fn) {
callWithAsyncErrorHandling(fn.bind(instance.proxy!), instance, type)
}
}
}
function applyMixins(
instance: ComponentInternalInstance,
mixins: ComponentOptions[],
deferredData: DataFn[],
deferredWatch: ComponentWatchOptions[],
deferredProvide: (Data | Function)[]
) {
for (let i = 0; i < mixins.length; i++) {
applyOptions(
instance,
mixins[i],
deferredData,
deferredWatch,
deferredProvide,
true
)
}
}
function resolveData(
instance: ComponentInternalInstance,
dataFn: DataFn,
publicThis: ComponentPublicInstance
) {
if (__DEV__ && !isFunction(dataFn)) {
warn(
`The data option must be a function. ` +
`Plain object usage is no longer supported.`
)
}
const data = dataFn.call(publicThis, publicThis)
if (__DEV__ && isPromise(data)) {
warn(
`data() returned a Promise - note data() cannot be async; If you ` +
`intend to perform data fetching before component renders, use ` +
`async setup() + <Suspense>.`
)
}
if (!isObject(data)) {
__DEV__ && warn(`data() should return an object.`)
} else if (instance.data === EMPTY_OBJ) {
instance.data = reactive(data)
} else {
// existing data: this is a mixin or extends.
extend(instance.data, data)
}
}
function createWatcher(
raw: ComponentWatchOptionItem,
ctx: Data,
publicThis: ComponentPublicInstance,
key: string
) {
const getter = key.includes('.')
? createPathGetter(publicThis, key)
: () => (publicThis as any)[key]
if (isString(raw)) {
const handler = ctx[raw]
if (isFunction(handler)) {
watch(getter, handler as WatchCallback)
} else if (__DEV__) {
warn(`Invalid watch handler specified by key "${raw}"`, handler)
}
} else if (isFunction(raw)) {
watch(getter, raw.bind(publicThis))
} else if (isObject(raw)) {
if (isArray(raw)) {
raw.forEach(r => createWatcher(r, ctx, publicThis, key))
} else {
const handler = isFunction(raw.handler)
? raw.handler.bind(publicThis)
: (ctx[raw.handler] as WatchCallback)
if (isFunction(handler)) {
watch(getter, handler, raw)
} else if (__DEV__) {
warn(`Invalid watch handler specified by key "${raw.handler}"`, handler)
}
}
} else if (__DEV__) {
warn(`Invalid watch option: "${key}"`, raw)
}
}
function createPathGetter(ctx: any, path: string) {
const segments = path.split('.')
return () => {
let cur = ctx
for (let i = 0; i < segments.length && cur; i++) {
cur = cur[segments[i]]
}
return cur
}
}
export function resolveMergedOptions(
instance: ComponentInternalInstance
): ComponentOptions {
const raw = instance.type as ComponentOptions
const { __merged, mixins, extends: extendsOptions } = raw
if (__merged) return __merged
const globalMixins = instance.appContext.mixins
if (!globalMixins.length && !mixins && !extendsOptions) return raw
const options = {}
globalMixins.forEach(m => mergeOptions(options, m, instance))
mergeOptions(options, raw, instance)
return (raw.__merged = options)
}
function mergeOptions(to: any, from: any, instance: ComponentInternalInstance) {
const strats = instance.appContext.config.optionMergeStrategies
const { mixins, extends: extendsOptions } = from
extendsOptions && mergeOptions(to, extendsOptions, instance)
mixins &&
mixins.forEach((m: ComponentOptionsMixin) => mergeOptions(to, m, instance))
for (const key in from) {
if (strats && hasOwn(strats, key)) {
to[key] = strats[key](to[key], from[key], instance.proxy, key)
} else {
to[key] = from[key]
}
}
}