HarmonyOS
目标:实现点赞和取消点赞,收藏和取消收藏
注意: 点赞和收藏是一个接口,取消点赞和取消收藏是一个接口,参数都一样合并在一个方法完成
实现步骤:
- 步骤1 准备接口参数类型
-
- QuestionOptParams
- 步骤2 封装操作方法,参数支持 操作类型 + 是点赞|收藏还是取消,根据条件操作
-
- questionOpt 参数: optType 和 flag
- 注意区分接口: 'question/opt' , 'question/unOpt'
- 步骤3 绑定事件,调用操作方法
第一步:数据类型
// 点赞/收藏, 取消点赞/取消收藏对象类型
export interface QuestionOptParams {
/**
* 试题id/面经id
*/
id: string;
/**
* 1点赞 2收藏
*/
optType: 1 | 2;
/**
* 0面试题 1面经
*/
type: 0 | 1;
}
第二步:封装函数
/**
* 点赞/收藏,取消点赞/取消收藏
* @param optType 1点赞 2收藏
* @param flag 0 取消点赞/取消收藏 1点赞/收藏
*/
async questionOpt(optType: 1 | 2, flag: 0 | 1) {
try {
// 1. 请求的参数
const data: QuestionOptParams = {
id: this.item.id,
type: 0,
optType
}
// 2. 发起请求
await http.request<null, QuestionOptParams>({
url: flag === 1 ? '/question/opt' : '/question/unOpt',
method: 'post',
data
})
// 3. 更新对象数据
// 3.1 如果是点赞
if (optType === 1) {
this.item.likeFlag = this.item.likeFlag === 1 ? 0 : 1
promptAction.showToast({ message: this.item.likeFlag === 1 ? '点赞成功' : '取消点赞' })
}
// 3.2 如果是收藏
if (optType === 2) {
this.item.collectFlag = this.item.collectFlag === 1 ? 0 : 1
promptAction.showToast({ message: this.item.collectFlag === 1 ? '收藏成功' : '取消收藏' })
}
} catch (e) {
promptAction.showToast({ message: '操作失败' })
}
}
第三步:调用方法 QuestionPage.ets
MenuItem({ content: this.item.likeFlag === 1 ? '取消点赞' : '点赞' })
.onClick(() => this.questionOpt(1, this.item.likeFlag === 1 ? 0 : 1))
MenuItem({ content: this.item.collectFlag === 1 ? '取消收藏' : '收藏' })
.onClick(() => this.questionOpt(2, this.item.collectFlag === 1 ? 0 : 1))
7329

被折叠的 条评论
为什么被折叠?



