点击锁定按钮,锁定按钮要变成解锁按钮,然后状态要从待绑定变成 已锁定(升级版)

文章目录

点击锁定按钮,锁定按钮要变成解锁按钮,然后状态要从待绑定变成 已锁定https://blog.csdn.net/m0_65152767/article/details/144810693

这篇博客中的内容,有一个bug,那就是我刷新页面,解锁按钮还是会变成锁定按钮,最后检查发现锁定按钮有一个字段是和后端关联的,我没有更新后端这个字段的值,所以也就造成我们只是临时的更改锁定按钮的状态,并没有持久化更改。


1、updateInviteCodeStatus

ts 复制代码
// 修改接口参数类型
export const updateInviteCodeStatus = (data: {
    inviteCodeId: number;
    statusName: string;
    isLocked: number; // 新增 isLocked 字段
  }) =>
  request({
    url: '/api/invite-codes/updateStatus',
    method: 'put',
    params: data, // params 中包含 isLocked 参数
  });

2、handleLock

ts 复制代码
  private async handleLock(row: any) {
    const newIsLocked = row.isLocked === 0 ? 1 : 0
    const newStatus = newIsLocked === 0
      ? InviteCodeStatus.EFFECTIVE.name
      : InviteCodeStatus.LOCKED.name

    this.$confirm(
      `确定要${row.isLocked === 0 ? '锁定' : '解锁'}该邀请码吗?`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
      .then(async() => {
        try {
          console.log('请求参数:', {
            inviteCodeId: row.id,
            statusName: newStatus,
            isLocked: newIsLocked, // 添加 isLocked 参数
          })

          // 调用后端的更新状态接口
          const response = await updateInviteCodeStatus({
            inviteCodeId: row.id,
            statusName: newStatus,
            isLocked: newIsLocked, // 添加 isLocked 参数
          })

          console.log('response.data:', response.data)
          console.log('typeof response.data', typeof response.data)

          if (response && response.data && typeof response.data === 'object' && 'status' in response.data) {

            const status = response.data.status
            const isLocked = response.data.isLocked

            // 调试步骤 1:打印状态值
            console.log('状态值:', status)
            console.log('后端返回的isLocked值:',isLocked)

            // 调试步骤 2:检查状态映射
            let statusObj
            try {
              statusObj = InviteCodeStatus.fromValue(status)
              console.log('映射后的状态:', statusObj)
            } catch (e) {
              console.error('状态映射错误:', e)
              this.$message.error('状态映射错误,请联系管理员')
              return
            }

            // 更新本地数据
            const index = this.tableData.findIndex(item => item.id === row.id)
            if (index !== -1) {
              this.$set(this.tableData, index, {
                ...this.tableData[index],
                // isLocked: newIsLocked,
                status: status, // 使用后端返回的 status 值
                isLocked: isLocked, // 使用后端返回的isLocked
              })
              console.log('更新后的行数据:', this.tableData[index])
            }

            this.$message.success(`${newIsLocked === 0 ? '解锁' : '锁定'}成功`)

            // 选择性地重新拉取数据,根据实际需求
            // await this.fetchInviteCodeList();
          } else {
            this.$message.error('更新失败')
          }
        } catch (error) {
          console.error('更新邀请码状态失败:', error)
          console.error('错误详情:', error.response || error.message)
          this.$message.error('更新邀请码状态失败:未知错误')
        }
      })
      .catch(() => { })
  }

3、InviteCodeController

java 复制代码
    @PutMapping("/updateStatus")
    public BaseResult updateInviteCodeStatus(
            @RequestParam Integer inviteCodeId,
            @RequestParam String statusName,
            @RequestParam Integer isLocked) {  // 添加 isLocked 参数
        try {
            // 获取 InviteCodeStatus 枚举值
            InviteCodeStatus status = InviteCodeStatus.fromName(statusName);
            // 调用service层更新状态的方法
            inviteCodeService.updateInviteCodeStatus(inviteCodeId, status.getValue(),isLocked);// 更新 isLocked
            // 获取更新后的邀请码数据
            Optional<InviteCode>  updatedInviteCodeOptional = inviteCodeService.getInviteCodeById(inviteCodeId);
            if(updatedInviteCodeOptional.isPresent()){
                InviteCode updatedInviteCode =  updatedInviteCodeOptional.get();
                // 构建返回数据
                Map<String,Object> data = new HashMap<>();
                data.put("status", updatedInviteCode.getStatus());
                data.put("isLocked", updatedInviteCode.getIsLocked()); // 添加 isLocked 字段
                return BaseResult.success("状态更新成功",data);
            }else {
                return BaseResult.success("状态更新成功");
            }
        } catch (IllegalArgumentException e) {
            return BaseResult.failure(BaseResult.PARAMETER_ERROR, e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return BaseResult.failure(500, "服务器内部错误" + e.getMessage());
        }
    }

4、InviteCodeService

java 复制代码
    @Transactional
    public void updateInviteCodeStatus(Integer inviteCodeId, Integer status, Integer isLocked) {
        Optional<InviteCode> inviteCodeOptional = inviteCodeRepository.findById(inviteCodeId);
        if (inviteCodeOptional.isPresent()) {
            InviteCode inviteCode = inviteCodeOptional.get();
            inviteCode.setStatus(status);
            inviteCode.setLastModifiedDate(LocalDateTime.now());// 更新最后修改时间
            inviteCode.setIsLocked(isLocked);
            inviteCodeRepository.save(inviteCode);
        } else {
            throw new IllegalArgumentException("Invalid inviteCode ID: " + inviteCodeId);
        }
    }
    
    public Optional<InviteCode> getInviteCodeById(Integer inviteCodeId) {
        return inviteCodeRepository.findById(inviteCodeId);
    }

5、CrudRepository

java 复制代码
public interface CrudRepository<T, ID> extends Repository<T, ID> {
			Optional<T> findById(ID var1);
			
			<S extends T> S save(S var1);
}
相关推荐
遇见~未来13 小时前
第三篇_现代布局_从弹性到网格
前端·css3
geovindu13 小时前
go:Template Method Pattern
开发语言·后端·设计模式·golang·模板方法模式
前端那点事13 小时前
Vue前端SEO优化全攻略(实操落地版,新手也能上手)
前端·vue.js
卷Java13 小时前
上下文压缩
开发语言·windows·python
日取其半万世不竭13 小时前
Minecraft Java版社区服搭建教程(Windows版)
java·开发语言·windows
Dxy123931021613 小时前
HTML 如何使用 SVG 画曲线
前端·算法·html
wjs202413 小时前
HTML 文本格式化
开发语言
白夜111713 小时前
C++任务调度与状态机
开发语言·c++·笔记
用户23678298016813 小时前
从零实现 GIF 制作工具:LZW 压缩与 Median Cut 色彩量化
前端·javascript
南宫萧幕13 小时前
MATLAB/Simulink 从零打通:HEV 能量管理 GA 联合仿真保姆级建模指南
开发语言·算法·matlab·汽车·控制·pid