当前位置: 首页 > 科技观察

在ArkUI的ETS中实现【slot】的功能

时间:2023-03-16 16:18:01 科技观察

更多内容请访问:https://harmonyos.51cto.com,与华为官网共建的鸿蒙技术社区,还有待时日ETS的发布,也有很多小伙伴通过ETS制作了很多漂亮的页面,但是在查看ETS的组件和API的时候发现现有版本的ETS并没有slot功能。经过一段时间的摸索,终于找到了曲线救国的方法来实现槽函数,让组件解耦。什么是插槽?了解slots的朋友可以略过vue官方的定义:slot是一组用于内容分发的API。呈现组件时,它将替换为“您的配置文件”。插槽可以包含任何模板代码。通俗点说,slot就像一个占位符,将组件外部的内容通过API分发给组件。实现步骤定义一个slot类来提供命名slot,所以定义一个slot类用于后续委托。这对实现并不重要,也没有定义。classSlot{name:string="default"builder:anyconstructor(name:string,builder:any){this.name=name;this.builder=builder}}创建一个组件CompA创建一个自定义组件CompA并提供两个的处理命名插槽,一个默认插槽,一个插槽2。@ComponentstructCompA{@Statetext:string=""@Statedata:string[]=[]@Stateslot:Slot=newSlot(null)build(){Column(){Column(){Text("CompA组件中的内容").fontColor("#00F").fontSize(16).margin(10)}Column(){Row(){if(this.slot.name=="default"){ForEach(["这是默认槽位【default】"],this.slot.builder)}if(this.slot.name=="slot2"){ForEach(this.data,this.slot.builder)}}}}}}构建页面组件一个Index页面,在页面中创建两个Buiderbulder1和builder2,并实例化两个Slot类slot1和slot2,将builder1和builder2分别赋予slot1和slot2。通过builder1中的Text组件显示一段文字。Builder2构建了一个稍微复杂的模型,设置了一个文本和一个二维码。@Entry@ComponentstructIndex{@Builderbuilder1(str:string){Text(str).fontSize(18).fontColor("#f00")}@Builderbuilder2(obj:any){Column(){Row(){Text(obj.title).fontSize(16)}Row(){QRCode(obj.title).width(100).height(100)}.margin(10)}.margin(10)}slot1:Slot=newSlot(this.builder1)slot2:Slot=newSlot(this.builder2,"slot2")build(){Flex({direction:FlexDirection.Column,alignItems:ItemAlign.Center,justifyContent:FlexAlign.Center}){Column(){CompA(){Text("这个不会显示").fontSize(24)}CompA({slot:this.slot1})CompA({slot:this.slot2,data:[{title:"这是第二个插入Slot"},{title:"http://www.baidu.com"}]})}}.width('100%').height('100%')}}显示效果:通过图片可以看出,builder1和builder2的真实位置在CompA的slot上。上面提到的关键点是不需要创建Slot类,因为实现原理是通过ForEach+Builder实现的,Builder也可以通过函数绑定到组件上。查看官方文档中的ForEach:所有代码供参考@Entry@ComponentstructIndex{@Builderbuilder1(str:string){Text(str).fontSize(18).fontColor("#f00")}@Builderbuilder2(obj:any){Column(){Row(){Text(obj.title).fontSize(16)}Row(){QRCode(obj.title).width(100).height(100)}.margin(10)}。保证金(10)}slot1:Slot=newSlot(this.builder1)slot2:Slot=newSlot(this.builder2,"slot2")build(){Flex({direction:FlexDirection.Column,alignItems:ItemAlign.Center,justifyContent:FlexAlign.Center}){Column(){CompA(){Text("这个不会显示").fontSize(24)}CompA({slot:this.slot1})CompA({slot:this.slot2,data:[{title:"这是第二个槽位"},{title:"http://www.baidu.com"}]})}}.width('100%').height('100%')}}@ComponentstructCompA{@Statetext:string=""@Statedata:string[]=[]@Stateslot:Slot=newSlot(null)build(){Column(){Column(){Text("CompA组件的内容").fontColor("#00F").fontSize(16).margin(10)}Column(){Row(){if(this.slot.name=="default"){ForEach(["this是默认插槽[default]"],this.slot.builder)}if(this.slot.name=="slot2"){ForEach(this.data,this.slot.builder)}}}}}}classSlot{name:string="default"builder:anyconstructor(builder:any,name?:string){name&&(this.name=name);this.builder=builder}}更多信息请访问:和华为官方Harmonyos技术社区共建https://harmonyos.51cto.com