状态管理@Prop、@Link装饰器

news/2024/7/21 8:17:59 标签: harmonyos

@Prop @Link

父子组件进行数据同步化
@prop 单向同步 只支持string、number、boolean、enum类型
负组件对象类型,总组件是对象类型
不可以是数组、any
不允许子组件初始化
@Link双向同步
父子类型一直:string、number、boolean、enum、object、class以及他们的数组
数组元素crud会引起嵌套类型以及数组中的对象熟悉无法出发视图更新
父组件传递,禁止子组件初始化

class Task2{
  static id:number = 1
  name:string = `任务:${Task2.id++}`
  state:boolean = false

}
//统一卡片样式
@Styles function card2(){
  .width('95%')
  .padding(20)
  .borderRadius(15)
  .backgroundColor(Color.White)
  .shadow({radius:5,color:'yellow',offsetX:2,offsetY:4})
}
//任务完成样式
@Extend(Text) function finishCard2(){
  .decoration({type:TextDecorationType.LineThrough})
  .backgroundColor('#B1B2B1')
}

class totalInfo{
  totalTask:number = 0
  finishTask:number = 0
}

@Entry
@Component
struct taskProvideConsume{
  //统计
  @State total: totalInfo = new totalInfo()
  build(){
    Column({space:10}) {
      //1.任务进度
     taskTest2({finishTask:this.total.finishTask,totalTask:this.total.totalTask})
      //2.新增任务按钮 //3.任务列表
      taskList2({total:$total})
    }
    .width('100%')
    .height('100%')
    .backgroundColor('#F1F2F3')
  }
}

@Component
struct taskTest2{
  @Prop totalTask:number
  @Prop finishTask:number
  build(){
    Row() {
      Text("任务进度:")
        .fontSize(40)
        .fontWeight(FontWeight.Bold)
      Stack() {
        Progress({
          value: this.finishTask,
          total: this.totalTask,
          type: ProgressType.Ring
        })
          .width('100')
        Row() {
          Text(this.finishTask.toString())
            .fontSize(24)
            .fontColor('blue')
          Text(' / ' + this.totalTask.toString())
            .fontSize(24)
        }
      }
    }
    .card2()
    .margin({ top: 10, bottom: 10 })
    .justifyContent(FlexAlign.SpaceEvenly)
  }
}

@Component
struct taskList2{
  //总任务数
  @Link total: totalInfo
  @State Tasks2:Task2[]=[]
  //创建一个更新函数
  handleTaskChange(){
    this.total.totalTask = this.Tasks2.length
    this.total.finishTask = this.Tasks2.filter(item => item.state).length
  }
  build(){
    Column(){
      Button('新增任务')
        .onClick(() => {
          this.Tasks2.push(new Task2())
          //this.totalTask = this.Tasks.length
          this.handleTaskChange()
        })
        .fontSize(20)
      List(){
        ForEach(
          this.Tasks2,
          (item:Task2, index) =>{
            ListItem(){
              Row(){
                Text(item.name)
                  .fontSize(25)
                Checkbox()
                  .select(item.state)
                  .onChange(val =>{
                    item.state = val
                    //完成的数量 = 任务列表中filter状态的长度
                    //this.finishTask = this.Tasks.filter(item => item.state).length
                    this.handleTaskChange()
                  })
              }
              .card2()
              .margin({top:15})
              .justifyContent(FlexAlign.SpaceBetween)
            }
            .swipeAction({end: this.DeleteCard(index)})
          })
      }
      .width('100%')
      .layoutWeight(1)
      .alignListItem(ListItemAlign.Center)
    }
  }
  @Builder DeleteCard(index:number){
    Button(){
      Image($r('app.media.ic_public_delete_filled'))
        .fillColor(Color.White)
        .width(20)
    }
    .width(40)
    .height(40)
    .type(ButtonType.Circle)
    .backgroundColor(Color.Red)
    .margin(5)
    .onClick(()=>{
      this.Tasks2.splice(index,1)
      this.handleTaskChange()
    })
  }
}

学习常见bug

A preview error may have occurred. Switch to the Log tab to view details

解决方法:
在这里插入图片描述

这个报错通常是路由跳转时发生的,首先查看路由表中是否有当前页面。
路由表路径: entry > src > main > resources > base > profile > main_pages.json

@ObjectLink、@Observed

用于设计嵌套对象或者数组元素为对进行双向数据同步

完整版任务进度

@Observed
class Task2{
  static id:number = 1
  name:string = `任务:${Task2.id++}`
  state:boolean = false

}
//统一卡片样式
@Styles function card2(){
  .width('95%')
  .padding(20)
  .borderRadius(15)
  .backgroundColor(Color.White)
  .shadow({radius:5,color:'yellow',offsetX:2,offsetY:4})
}
//任务完成样式
@Extend(Text) function finishCard2(){
  .decoration({type:TextDecorationType.LineThrough})
  .backgroundColor('#B1B2B1')
}

class totalInfo{
  totalTask:number = 0
  finishTask:number = 0
}

@Entry
@Component
struct taskProvideConsume{
  //统计
  @State total: totalInfo = new totalInfo()
  build(){
    Column({space:10}) {
      //1.任务进度
     taskTest2({finishTask:this.total.finishTask,totalTask:this.total.totalTask})
      //2.新增任务按钮 //3.任务列表
      taskList2({total:$total})
    }
    .width('100%')
    .height('100%')
    .backgroundColor('#F1F2F3')
  }
}

@Component
struct taskTest2{
  @Prop totalTask:number
  @Prop finishTask:number
  build(){
    Row() {
      Text("任务进度:")
        .fontSize(40)
        .fontWeight(FontWeight.Bold)
      Stack() {
        Progress({
          value: this.finishTask,
          total: this.totalTask,
          type: ProgressType.Ring
        })
          .width('100')
        Row() {
          Text(this.finishTask.toString())
            .fontSize(24)
            .fontColor('blue')
          Text(' / ' + this.totalTask.toString())
            .fontSize(24)
        }
      }
    }
    .card2()
    .margin({ top: 10, bottom: 10 })
    .justifyContent(FlexAlign.SpaceEvenly)
  }
}

@Component
struct taskList2{
  //总任务数
  @Link total: totalInfo
  @State Tasks2:Task2[]=[]
  //创建一个更新函数
  handleTaskChange(){
    this.total.totalTask = this.Tasks2.length
    this.total.finishTask = this.Tasks2.filter(item => item.state).length
  }
  build(){
    Column(){
      Button('新增任务')
        .onClick(() => {
          this.Tasks2.push(new Task2())
          //this.totalTask = this.Tasks.length
          this.handleTaskChange()
        })
        .fontSize(20)
      List(){
        ForEach(
          this.Tasks2,
          (item:Task2, index) =>{
            ListItem(){//传参 传函数
              itemList({ item: item,onTaskChange:this.handleTaskChange.bind(this)})
            }
            .swipeAction({end: this.DeleteCard(index)})
          })
      }
      .width('100%')
      .layoutWeight(1)
      .alignListItem(ListItemAlign.Center)
    }
  }
  @Builder DeleteCard(index:number){
    Button(){
      Image($r('app.media.ic_public_delete_filled'))
        .fillColor(Color.White)
        .width(20)
    }
    .width(40)
    .height(40)
    .type(ButtonType.Circle)
    .backgroundColor(Color.Red)
    .margin(5)
    .onClick(()=>{
      this.Tasks2.splice(index,1)
      this.handleTaskChange()
    })
  }
}
@Component
struct itemList{
  @ObjectLink item:Task2
  onTaskChange: ()=>void
  build(){
    Row(){
      if (this.item.state){
        Text(this.item.name)
          .fontSize(25)
          .finishCard2()
      }else {
        Text(this.item.name)
          .fontSize(25)
      }
      Checkbox()
        .select(this.item.state)
        .onChange(val =>{
          this.item.state = val
          //完成的数量 = 任务列表中filter状态的长度
          //this.finishTask = this.Tasks.filter(item => item.state).length
          //this.handleTaskChange()
          this.onTaskChange()
        })
    }
    .card2()
    .margin({top:15})
    .justifyContent(FlexAlign.SpaceBetween)
  }
}

http://www.niftyadmin.cn/n/5446633.html

相关文章

如何使用命令行查看服务器的核心数和内存大小

在管理服务器时,了解服务器的硬件配置是至关重要的。本文将介绍如何使用命令行来查看服务器的核心数和内存大小,涵盖了常见的 Linux、Windows 和 macOS 操作系统。 Linux 查看核心数 你可以使用下面的命令来查看CPU的物理核心数和逻辑核心数&#xff…

微服务day05(中) -- ES索引库操作

索引库就类似数据库表,mapping映射就类似表的结构。 我们要向es中存储数据,必须先创建“库”和“表”。 2.1.mapping映射属性 mapping是对索引库中文档的约束,常见的mapping属性包括: type:字段数据类型,…

Standard C String Character(标准c字符和字符串)

1. atof 语法&#xff1a; #include<stdlib.h> double atof(const char *str); 功能&#xff1a;将字符串str转换成一个双精度数值并返回结果。参数str必须以有效数字开头&#xff0c;但是允许以"E"或"e"除外的任意非数字字符结尾。 #include<i…

springboot287基于javaEE的校园二手书交易平台的设计与实现

校园二手书交易平台设计与实现 摘 要 信息数据从传统到当代&#xff0c;是一直在变革当中&#xff0c;突如其来的互联网让传统的信息管理看到了革命性的曙光&#xff0c;因为传统信息管理从时效性&#xff0c;还是安全性&#xff0c;还是可操作性等各个方面来讲&#xff0c;遇…

算法体系-12 第 十二 二叉树的基本算法 下

一 实现二叉树的按层遍历 1.1 描述 1&#xff09;其实就是宽度优先遍历&#xff0c;用队列 2&#xff09;可以通过设置flag变量的方式&#xff0c;来发现某一层的结束&#xff08;看题目&#xff09;看下边的第四题解答 1.2 代码 public class Code01_LevelTraversalBT {publ…

20240316-1-向量化搜索

向量化搜索 在高维空间内快速搜索最近邻&#xff08;Approximate Nearest Neighbor&#xff09;。召回中&#xff0c;Embedding向量的搜索。 FAISS、kd-tree、局部敏感哈希、【Amnoy、HNSW】 FAISS faiss是Facebook的AI团队开源的一套用于做聚类或者相似性搜索的软件库&…

如何快速搭建一个完整的vue2+element-ui的项目-二

技术细节-继续配置 提示&#xff1a;你以为这样就完了吗,其实还有很多东西需要我们自己手写的 例如&#xff1a; element-ui的配置样式重置配置src使用的配置elinst配置axios异步请求的二次封转配置语言国际化配置(这个看需求,我这里就不用配置了)vuex的配置mixins的配置开发环…

c++学习笔记(9)

1. 在 C 中&#xff0c;表达式 (i & 1) 是一个位运算表达式。它使用了按位与操作符 & 来对变量 i 和数字 1 进行二进制的按位与操作。 按位与操作符 & 会比较两个数的二进制表示中的对应位&#xff0c;如果两个相应的二进制位都为 1&#xff0c;则该位的结果值为…