0
# Component System
1
2
Comprehensive component system with properties, methods, lifecycle events, and component relationships for creating reusable WeChat Mini Program components.
3
4
## Capabilities
5
6
### Component Constructor
7
8
Creates a custom WeChat Mini Program component with properties, data, methods, and lifecycle hooks.
9
10
```typescript { .api }
11
/**
12
* Create a WeChat Mini Program component
13
* @param options - Component configuration with properties, data, methods, and lifecycle
14
*/
15
function Component<
16
TData extends WechatMiniprogram.Component.DataOption,
17
TProperty extends WechatMiniprogram.Component.PropertyOption,
18
TMethod extends WechatMiniprogram.Component.MethodOption
19
>(
20
options: WechatMiniprogram.Component.Option<TData, TProperty, TMethod>
21
): void;
22
```
23
24
**Usage Examples:**
25
26
```typescript
27
Component({
28
properties: {
29
title: String,
30
count: {
31
type: Number,
32
value: 0
33
},
34
disabled: {
35
type: Boolean,
36
value: false
37
},
38
items: {
39
type: Array,
40
value: []
41
}
42
},
43
data: {
44
visible: true,
45
loading: false
46
},
47
methods: {
48
handleTap() {
49
if (!this.properties.disabled) {
50
this.triggerEvent('itemTap', {
51
title: this.properties.title,
52
count: this.properties.count
53
});
54
}
55
},
56
show() {
57
this.setData({ visible: true });
58
},
59
hide() {
60
this.setData({ visible: false });
61
}
62
},
63
lifetimes: {
64
created() {
65
console.log('Component created');
66
},
67
attached() {
68
console.log('Component attached to page');
69
},
70
ready() {
71
console.log('Component ready - initial render complete');
72
},
73
detached() {
74
console.log('Component detached from page');
75
}
76
}
77
});
78
```
79
80
### Behavior Constructor
81
82
Creates reusable behavior mixins that can be shared across multiple components.
83
84
```typescript { .api }
85
/**
86
* Create a reusable behavior for components
87
* @param options - Behavior configuration with shared properties, data, and methods
88
*/
89
function Behavior<
90
TData extends WechatMiniprogram.Behavior.DataOption,
91
TProperty extends WechatMiniprogram.Behavior.PropertyOption,
92
TMethod extends WechatMiniprogram.Behavior.MethodOption
93
>(
94
options: WechatMiniprogram.Behavior.Option<TData, TProperty, TMethod>
95
): void;
96
```
97
98
**Usage Examples:**
99
100
```typescript
101
// Define a behavior for common loading functionality
102
const LoadingBehavior = Behavior({
103
data: {
104
loading: false,
105
error: null
106
},
107
methods: {
108
setLoading(loading: boolean) {
109
this.setData({ loading, error: null });
110
},
111
setError(error: string) {
112
this.setData({ loading: false, error });
113
}
114
}
115
});
116
117
// Use behavior in component
118
Component({
119
behaviors: [LoadingBehavior],
120
methods: {
121
async fetchData() {
122
this.setLoading(true);
123
try {
124
const data = await this.requestData();
125
this.setData({ data });
126
} catch (error) {
127
this.setError(error.message);
128
}
129
}
130
}
131
});
132
```
133
134
## Component Instance Methods
135
136
```typescript { .api }
137
interface WechatMiniprogram.Component.Instance<TData, TProperty, TMethod> {
138
/** Component data */
139
readonly data: TData;
140
141
/** Component properties */
142
readonly properties: TProperty;
143
144
/** Update component data and trigger re-render */
145
setData(data: Partial<TData>, callback?: () => void): void;
146
147
/** Trigger custom event to parent component */
148
triggerEvent(
149
name: string,
150
detail?: any,
151
options?: WechatMiniprogram.Component.TriggerEventOption
152
): void;
153
154
/** Create selector query for DOM operations */
155
createSelectorQuery(): WechatMiniprogram.SelectorQuery;
156
157
/** Create intersection observer for visibility detection */
158
createIntersectionObserver(
159
options?: WechatMiniprogram.CreateIntersectionObserverOption
160
): WechatMiniprogram.IntersectionObserver;
161
162
/** Create media query observer for responsive design */
163
createMediaQueryObserver(): WechatMiniprogram.MediaQueryObserver;
164
165
/** Select child component by selector */
166
selectComponent(selector: string): WechatMiniprogram.Component.Instance<any, any, any> | null;
167
168
/** Select all child components by selector */
169
selectAllComponents(selector: string): WechatMiniprogram.Component.Instance<any, any, any>[];
170
171
/** Get related components */
172
getRelationNodes(relationKey: string): WechatMiniprogram.Component.Instance<any, any, any>[];
173
174
/** Batch data updates for performance */
175
groupSetData(callback?: () => void): void;
176
177
/** Get custom tab bar component (if applicable) */
178
getTabBar(): WechatMiniprogram.Component.Instance<any, any, any> | null;
179
180
/** Get unique page identifier */
181
getPageId(): string;
182
183
/** Animate elements with keyframes */
184
animate(
185
selector: string,
186
keyframes: WechatMiniprogram.Component.PropertyAnimation[],
187
duration: number,
188
callback?: () => void
189
): void;
190
191
/** Clear animations on elements */
192
clearAnimation(
193
selector: string,
194
options?: WechatMiniprogram.Component.ClearAnimationOptions,
195
callback?: () => void
196
): void;
197
}
198
199
interface WechatMiniprogram.Component.TriggerEventOption {
200
/** Whether the event bubbles up */
201
bubbles?: boolean;
202
/** Whether the event is composed */
203
composed?: boolean;
204
/** Whether the event can be captured */
205
capturePhase?: boolean;
206
}
207
```
208
209
## Component Lifecycle
210
211
```typescript { .api }
212
interface WechatMiniprogram.Component.Option<TData, TProperty, TMethod> {
213
/** Component properties definition */
214
properties?: TProperty;
215
216
/** Initial component data */
217
data?: TData;
218
219
/** Component methods */
220
methods?: TMethod;
221
222
/** Applied behaviors */
223
behaviors?: any[];
224
225
/** Component lifecycle methods */
226
lifetimes?: {
227
/** Component instance created */
228
created?(): void;
229
/** Component attached to page DOM */
230
attached?(): void;
231
/** Component ready - initial render complete */
232
ready?(): void;
233
/** Component moved in DOM */
234
moved?(): void;
235
/** Component detached from page DOM */
236
detached?(): void;
237
/** Component error occurred */
238
error?(error: Error): void;
239
};
240
241
/** Page lifecycle listeners */
242
pageLifetimes?: {
243
/** Page shown */
244
show?(): void;
245
/** Page hidden */
246
hide?(): void;
247
/** Page resized */
248
resize?(size: { windowWidth: number; windowHeight: number }): void;
249
/** Route animation done */
250
routeDone?(): void;
251
};
252
253
/** Data observers */
254
observers?: {
255
[key: string]: (...args: any[]) => void;
256
};
257
258
/** Component relations */
259
relations?: {
260
[key: string]: WechatMiniprogram.Component.RelationOption;
261
};
262
263
/** Export methods to parent */
264
export?(): Record<string, any>;
265
266
/** External classes for styling */
267
externalClasses?: string[];
268
269
/** Options configuration */
270
options?: {
271
/** Virtual host configuration */
272
virtualHost?: boolean;
273
/** Multiple slots support */
274
multipleSlots?: boolean;
275
/** Add global class support */
276
addGlobalClass?: boolean;
277
/** Style isolation */
278
styleIsolation?: 'isolated' | 'apply-shared' | 'shared';
279
};
280
}
281
282
interface WechatMiniprogram.Component.RelationOption {
283
/** Relation type */
284
type: 'parent' | 'child' | 'ancestor' | 'descendant';
285
/** Relation target component */
286
target?: string;
287
/** Linked callback */
288
linked?(target: WechatMiniprogram.Component.Instance<any, any, any>): void;
289
/** Link changed callback */
290
linkChanged?(target: WechatMiniprogram.Component.Instance<any, any, any>): void;
291
/** Unlinked callback */
292
unlinked?(target: WechatMiniprogram.Component.Instance<any, any, any>): void;
293
}
294
```
295
296
## Property System
297
298
```typescript { .api }
299
interface WechatMiniprogram.Component.PropertyOption {
300
[key: string]: WechatMiniprogram.Component.AllProperty;
301
}
302
303
type WechatMiniprogram.Component.AllProperty =
304
| WechatMiniprogram.Component.PropertyType
305
| WechatMiniprogram.Component.FullProperty;
306
307
interface WechatMiniprogram.Component.FullProperty {
308
/** Property type */
309
type: WechatMiniprogram.Component.PropertyType;
310
/** Default value */
311
value?: any;
312
/** Property observer */
313
observer?(newVal: any, oldVal: any, changedPath: string): void;
314
/** Optional property */
315
optionalTypes?: WechatMiniprogram.Component.PropertyType[];
316
}
317
318
type WechatMiniprogram.Component.PropertyType =
319
| StringConstructor
320
| NumberConstructor
321
| BooleanConstructor
322
| ArrayConstructor
323
| ObjectConstructor
324
| null;
325
```
326
327
**Usage Examples:**
328
329
```typescript
330
Component({
331
properties: {
332
// Simple property types
333
title: String,
334
count: Number,
335
visible: Boolean,
336
items: Array,
337
config: Object,
338
339
// Full property definitions
340
status: {
341
type: String,
342
value: 'normal',
343
observer(newVal, oldVal) {
344
console.log(`Status changed from ${oldVal} to ${newVal}`);
345
}
346
},
347
348
// Optional types
349
value: {
350
type: String,
351
optionalTypes: [Number],
352
value: ''
353
}
354
}
355
});
356
```
357
358
## Animation System
359
360
```typescript { .api }
361
// Animation keyframes
362
interface WechatMiniprogram.Component.PropertyAnimation {
363
[property: string]: any;
364
}
365
366
// Clear animation options
367
interface WechatMiniprogram.Component.ClearAnimationOptions {
368
[property: string]: boolean;
369
}
370
```
371
372
**Usage Examples:**
373
374
```typescript
375
Component({
376
methods: {
377
animateButton() {
378
this.animate('.button', [
379
{ opacity: 1, rotate: 0 },
380
{ opacity: 0.5, rotate: 45 },
381
{ opacity: 1, rotate: 90 }
382
], 1000, () => {
383
console.log('Animation complete');
384
});
385
},
386
387
stopAnimation() {
388
this.clearAnimation('.button', {
389
opacity: true,
390
rotate: true
391
});
392
}
393
}
394
});
395
```
396
397
## Selector Query System
398
399
```typescript { .api }
400
interface WechatMiniprogram.SelectorQuery {
401
/** Select element by ID */
402
select(selector: string): WechatMiniprogram.NodesRef;
403
404
/** Select all elements by selector */
405
selectAll(selector: string): WechatMiniprogram.NodesRef;
406
407
/** Select viewport */
408
selectViewport(): WechatMiniprogram.NodesRef;
409
410
/** Execute query */
411
exec(callback?: (res: any[]) => void): WechatMiniprogram.SelectorQuery;
412
}
413
414
interface WechatMiniprogram.NodesRef {
415
/** Get bounding client rect */
416
boundingClientRect(
417
callback?: (rect: WechatMiniprogram.BoundingClientRectResult) => void
418
): WechatMiniprogram.SelectorQuery;
419
420
/** Get scroll offset */
421
scrollOffset(
422
callback?: (res: WechatMiniprogram.ScrollOffsetResult) => void
423
): WechatMiniprogram.SelectorQuery;
424
425
/** Get context (canvas, video, etc.) */
426
context(
427
callback?: (res: { context: any }) => void
428
): WechatMiniprogram.SelectorQuery;
429
}
430
```
431
432
## Types
433
434
```typescript { .api }
435
namespace WechatMiniprogram.Component {
436
interface DataOption {
437
[key: string]: any;
438
}
439
440
interface MethodOption {
441
[key: string]: (...args: any[]) => any;
442
}
443
444
interface Instance<TData, TProperty, TMethod> {
445
readonly data: TData;
446
readonly properties: TProperty;
447
setData(data: Partial<TData>, callback?: () => void): void;
448
triggerEvent(name: string, detail?: any, options?: TriggerEventOption): void;
449
}
450
}
451
452
namespace WechatMiniprogram.Behavior {
453
interface DataOption {
454
[key: string]: any;
455
}
456
457
interface PropertyOption {
458
[key: string]: any;
459
}
460
461
interface MethodOption {
462
[key: string]: (...args: any[]) => any;
463
}
464
465
interface Option<TData, TProperty, TMethod> {
466
properties?: TProperty;
467
data?: TData;
468
methods?: TMethod;
469
behaviors?: any[];
470
}
471
}
472
```