优化代码篇一(调接口的写法)

2024-01-18 20:40:05 浏览数 (1)

背景1:

今日将代码进行了优化,就是单选框里,点击确定分别调用不同的接口 效果如图:

上代码:

代码语言:javascript复制
 //修改房间状态
    updateRoomStatus() {
      let apiMethod=''
      apiMethod=this.roomStatus===0?'changeRoomStatusSelf':'changeRoomStatusIdle';//本质上是定义一个变量,对变量进行判断
        this.$api.building[apiMethod](this.id)
          .then(
            res => {
            if (res && res.code === 0) {
              this.$message({
                message: "修改成功",
                type: "success"
              });
              this.dialogRoomStatus = false;
              this.cacheIndex = this.currentIndex;
              this.getRoomList({
                buildingId: this.roomDetail.room.buildingId
              });
              this.getRoomStatusCount(this.roomDetail.room.buildingId);
            }
          })
    },

背景2:

调用数据接口后,loading写在了finally的后面

思考:

为什么要加finally,有什么好处吗? 还有就是finally后面可以加catch,但是有必要吗?

代码语言:javascript复制
 initData() {
      this.loading = true;
      const { page, size } = this.pagingProps;
      DrugDeliverServiceList.list(page, size, this.form)
        .then(res => {
          if (res.code === 0) {
            const data = res.result;
            this.tableData = [];
            this.tableData = data.content.map(item => {
              return {
                ...item,
                isLack: item.isLack === 1 ? "是" : "否",
                management: this.changeData(item.dmanagement)
              };
            });
            this.pagingProps.total = data.totalElements;
          }
        })
        .finally(() => {
          this.loading = false;//loading写在了finally的后面
        });
    },

0 人点赞