HarmonyOS 点赞功能(适用API12以上版本)

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))
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值