• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# @Consume and @Provide
2
3
4As the data provider, @Provide can update the data of child nodes and trigger page rendering. After @Consume detects that the @Provide data is updated, it will initiate re-rendering of the current view.
5
6
7  Table1 @Provide
8
9| Name | Description |
10| -------- | -------- |
11| Decorator parameter | A constant of the string type, which is used to set an alias for a decorated variable. If an alias is specified, implement the data update for this alias. If there is no alias, use the variable name as the alias. @Provide("_alias_") is recommended. |
12| Synchronization mechanism | The @Provide decorated variable is similar to the @state variable. You can modify the variable to re-render the page. You can also modify the @Consume decorated variable to modify the @State decorated variable reversely. |
13| Initial value | The initial value must be set. |
14| Page re-rendering scenarios | The following will trigger page re-rendering:<br/>- Changes of variables in primitive types (boolean, string, and number)<br/>- Changes of the @Observed decorated classes or their attributes<br/>- Adding, deleting, or updatingelements in an array |
15
16
17  Table2 @Consume
18
19| Type | Description |
20| -------- | -------- |
21| Initial value | No default value can be set. |
22
23
24> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**:
25> To avoid infinite loops caused by circular reference, exercise caution when using @Provide and @Consume.
26
27
28The description of other attributes is the same as that of @Provide.
29
30
31
32```
33@Entry
34@Component
35struct CompA {
36    @Provide("reviewVote") reviewVotes : number = 0;
37
38    build() {
39        Column() {
40            CompB()
41            Button() {
42                Text(`${this.reviewVotes}`)
43                    .fontSize(30)
44            }
45            .onClick(() => {
46                this.reviewVotes += 1;
47            })
48        }
49    }
50}
51
52@Component
53struct CompB {
54    build() {
55        Column() {
56            CompC()
57        }
58    }
59}
60
61@Component
62struct CompC {
63    @Consume("reviewVote") reviewVotes : number;
64    build() {
65        Column() {
66            Button() {
67                Text(`${this.reviewVotes}`)
68                    .fontSize(30)
69            }
70            .onClick(() => {
71                this.reviewVotes += 1;
72            })
73        }
74    }
75}
76```
77