写点什么

HarmonyOS 5.0 应用开发——V2 装饰器 @local 的使用

作者:高心星
  • 2025-09-15
    江苏
  • 本文字数:1206 字

    阅读完需:约 4 分钟

HarmonyOS 5.0应用开发——V2装饰器@local的使用

【高心星出品】

概念

组件内部状态管理 @Local 是专为 @ComponentV2 组件设计的装饰器,用于声明组件私有状态。被装饰的变量必须在组件内部初始化,禁止从父组件外部传入初始值(如Child({count: 10})的写法会报错),确保状态封装性。


观测能力


  • 支持类型:基本类型(number、string、boolean)、Object、class、Array、Set、Map、Date 等内嵌类型,以及联合类型 1。

  • 变化触发机制:

  • 简单类型(如 number):赋值操作触发 UI 刷新(如this.count++)。

  • 对象类型:仅整体赋值时触发(如替换整个对象this.obj = new MyClass())。

  • 数组/集合类型:整体赋值或调用特定 API(如push()set())时触发。


与 @State 的对比


使用场景

基本状态管理:


Button 绑定 local 装饰的变量 count,count 值改变引起 button 刷新。


@Entry@ComponentV2struct Index {  @Local count: number = 1;
build() { Column(){ Button('点击次数:'+this.count) .width('60%') .onClick(()=>{ this.count+=1 }) } .height('100%') .width('100%') .justifyContent(FlexAlign.Center) }}
复制代码


装饰数组的情况:


button 绑定数据源 datas 的长度,list 绑定数据源 datas,当数据源调用 push api 或者元素更新的时候会引起 UI 刷新。


@Entry@ComponentV2struct Localpage {  @Local datas:number[]=[1,2,3,4,5,6,7,8,9,10]  build() {   Column({space:20}){     Button('列表长度:'+this.datas.length)       .width('60%')       .onClick(()=>{         // 调用api会被观察        // this.datas.push(this.datas.length+1)        //  更新数组项也会被观察         this.datas[this.datas.length-1]=0       })     List(){       Repeat<number>(this.datas).each((item:RepeatItem<number>)=>{         ListItem(){           Text('列表项:'+item.item)             .fontSize(30)             .fontWeight(FontWeight.Bolder)             .padding(10)             .textAlign(TextAlign.Center)         }       })     }     .width('100%')     .divider({strokeWidth:2})   }    .height('100%')    .width('100%')  }}
复制代码


不可以从父组件向子组件传值


@ComponentV2struct child {  @Local count: number = 10
build() { Column() { Button('child count: ' + this.count) .width('60%') .onClick(() => { this.count += 1 }) } .width('100%') .padding(20) }}
@Entry@ComponentV2struct Localpage1 { @Local count: number = 11
build() { Column() { // 有问题不能外部传值 // child({count:11}) // child({count:this.count}) // 没问题 child() } .justifyContent(FlexAlign.Center) .height('100%') .width('100%') }}
复制代码


发布于: 刚刚阅读数: 3
用户头像

高心星

关注

天将降大任于斯人也,必先苦其心志。 2024-10-17 加入

华为开发者专家(HDE)。 10年教学经验,兼任多家科技公司技术顾问。先后从事JavaEE项目开发、Python爬虫、HarmonyOS移动应用开发等课程的教学工作。参与开发《鸿蒙应用开发基础》和《鸿蒙项目实战》等课程。

评论

发布
暂无评论
HarmonyOS 5.0应用开发——V2装饰器@local的使用_鸿蒙_高心星_InfoQ写作社区