2024年3月17日
- 要实现的效果图如下;
源代码如下:
// 任务类
class Task {
static id: number = 1
// 任务名称
name: string = `任务${Task.id++}`
// 任务状态是否完成
finished: boolean = false
}
// 统一的卡片样式函数
@Styles function card () {
.width('95%')
.padding(20)
.backgroundColor(Color.White)
.borderRadius(15)
.shadow({radius: 6, color: '#1F000000', offsetX: 2, offsetY: 4})
}
// 任务完成样式函数(Text组件特有属性)
@Extend(Text) function finishedTask() {
.decoration({ type: TextDecorationType.LineThrough})
.fontColor('#B1B2B1')
}
@Entry
@Component
struct PropPage {
// 任务总数量
@State totalTask: number = 0
// 已完成任务数量
@State finishTask: number = 0
// 任务列表
@State tasks: Task[] = []
// 局部自定义函数
handleTaskChange() {
// 1. 更新总任务
this.totalTask = this.tasks.length // 总任务就是数组的长度
// 2. 更新已完成的任务
this.finishTask = this.tasks.filter(item => item.finished).length // 通过filter方法过滤 finished状态为true的个数,然后赋值更新!
}
build() {
Column({ space: 10}) {
// 1. 任务进度
Row() {
Text('任务进度:')
.fontSize(30)
.fontWeight(FontWeight.Bold)
// 层叠容器
Stack(){
// 进度条组件
Progress({
value: this.finishTask,
total: this.tasks.length, // 最大任务数等于数组长度
type: ProgressType.Ring
})
.width(100)
// 任务进度对比数
Row(){
Text(this.finishTask.toString())
.fontSize(20)
Text(" / " + this.totalTask.toString())
.fontSize(20)
}
}
}
.width('100%')
.justifyContent(FlexAlign.SpaceEvenly)
.margin({top: 20, bottom: 10})
// 2. 新增任务按钮
Row(){
Button('新增任务')
.width(100)
.backgroundColor('#36D')
.onClick(() => {
// 1. 新增任务条数
this.tasks.push(new Task()) // 将任务类添加到数组中
// 2. 更新总任务
// this.totalTask = this.tasks.length // 总任务就是数组的长度
this.handleTaskChange()
})
}
.margin({bottom: 24})
// 3. 任务状态列表
List({ space: 10, initialIndex: 0}) {
// 遍历列表
ForEach(
this.tasks,
(item: Task, index) => {
ListItem() {
Row(){
Text(item.name)
.fontSize(20)
Checkbox()
// 是否选中就是取决于开关
.select(item.finished)
.onChange(change => {
// 1. 更新勾选状态值
item.finished = change
// 3. 更新已完成的任务
// this.finishTask = this.tasks.filter(item => item.finished).length // 通过filter方法过滤 finished状态为true的个数,然后赋值更新!
this.handleTaskChange()
})
}
.card()
.justifyContent(FlexAlign.SpaceBetween)
}
// 左滑事件调用按钮模块函数
.swipeAction({ end: this.DeleteButton(index) })
})
}
.width('100%')
.alignListItem(ListItemAlign.Center)
.layoutWeight(1)
}
.width('100%')
.height('100%')
.backgroundColor('#F1F2F3')
.padding(10)
}
/**
* DeleteButton 左滑删除按钮局部构建函数
* @param index
*/
@Builder DeleteButton (index: number) {
Button() {
Image($r('app.media.button_delete'))
.width(20)
// SVG图片颜色的设置
.fillColor(Color.White)
}
.width(40)
.height(40)
.type(ButtonType.Circle)
// Button组件按压效果
.stateEffect(true)
.backgroundColor(Color.Red)
.margin(5)
.onClick(() => {
// 1、点击删除后,更新任务列表
this.tasks.splice(index, 1)
// 2. 调用方法,更新任务进度的总数个完成数量
this.handleTaskChange()
})
}
}