组件之间的数据同步,@State,@Prop,@Watch装饰器

DevEco Studio 版本:DevEco Studio NEXT Developer Preview2
HarmonyOS API 版本:4.1.0(11)

组件之间的数据同步,@State,@Prop,@Watch 装饰器

这里是一个使用的@State,@Prop,@Watch 装饰器做组件之间的数据同步的 demo。

父组件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
@Component
struct SearchResultPage {
@State input: string = '';
@State searchWord: string = ''

aboutToAppear(): void {
this.syncSearchWord(this.input)
}

build() {
Column() {
SearchDramaResultList({ searchWord: this.searchWord }).layoutWeight(1)
}
.width('100%')
.height('100%')
}

syncSearchWord(keyword: string) {
if (keyword == '') return;
this.searchWord = keyword
}
}

子组件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@Component
export struct SearchDramaResultList {
@Prop @Watch('requestData') searchWord: string;
@State data?: SearchSeasonVo[] | null = null
private vm = new SearchVM()
// 需绑定列表或宫格组件
private scroller: Scroller = new Scroller();

aboutToAppear(): void {
// request data.
this.requestData()
}

requestData(propName: string) {
console.log("requestData: searchWord=", this.searchWord, ",propName=", propName);
// do data request with searchWord
}
}

组件之间的数据同步,@State,@Prop,@Watch装饰器

https://denchopen.github.io/blog/2024/05/15/鸿蒙-自定义组件之间的数据同步/

作者

Dench

发布于

2024-05-15

更新于

2024-05-15

许可协议

CC BY-NC-SA 4.0

Your browser is out-of-date!

Update your browser to view this website correctly.&npsb;Update my browser now

×