中国优质的IT技术网站
专业IT技术创作平台
IT职业在线教育平台
HarmonyOS 是否有类似vue里的子组件通过emit触发父组件里方法的api ?
微信扫码分享
//父组件调用子组件的方法参考代码: @Component struct Child { @State private text: string = '初始值' private controller: ChildController = new ChildController(); aboutToAppear() { if(this.controller) { //给controller对应的方法赋值 this.controller.changeText = this.changeText } } //封装的能力 private changeText = (value: string) =>{ this.text = value } build() { Column() { Text(this.text) } } } //定义controller对象 class ChildController { changeText = (value: string) => {} } @Entry @Component struct Parent { private ChildRef = new ChildController() build() { Column() { Text('调用Child的changeText').fontSize('18vp').fontColor(Color.Gray) Divider() Child({ controller:this. ChildRef }) Button('Parent调用childer的changeText').onClick(() => { this.ChildRef.changeText('Parent调用childer的changeText') }) } .justifyContent(FlexAlign.Center) .width("100%") .height("100%") } } //子组件调用父组件里的方法: @Entry @Component struct Index12 { clickFunc (data:number){ console.log(data.toString()) } build() { Row() { Column() { child({click:(data:number):void=>this.clickFunc(data)}) } .width('100%') } .height('100%') } } @Component export struct child { click?=(data:number)=>{}; build() { Row() { Column() { Text('点击子组件') .onClick(()=>{ if (this.click != undefined ) { this.click(123); } }) } .width('100%') } .height('100%') } }