如何优雅的写一个新增和修改的公用接口方法

553 阅读1分钟

这篇文章适用于多个接口公用一个接口方法。

前言

例如,你以前在写新增,编辑;批量操作,如批量审核,批量开发,批量完成等等可能会写多个方法,这也许是你刚入行的时候这么写面单时间久了之后你会发现有很多写法,函数方法封装,公共代码抽离等,这些将是你走向中高级前端的必经之路。废话不多说,上案列

image.png

image.png

可能以前你会这样写,但非常不推荐

这样看起来无非多两个判断,多写了个方法

methods: {
    // 提交表单
    handleSubmit1(name) {
      let sendData = JSON.parse(JSON.stringify(this.form))
      this.$refs[name].validate(async valid => {
        if (valid) {
          if (this.form.id) {
            relationMapApi.addSyscLogisticsCause(sendData).then(res => {
              if (res.data.success) {
                this.$Message.success({ content: `新增成功`, duration: 3 })
                this.modal1 = false
                this.getList() // 刷新查询列表
                this.form = this.$options.data().form // 初始化form
              } else {
                this.$Message.error(res.data.errorMsg || '服务端错误')
              }
            }).catch(err => {
              console.log(err)
            })
          } else {
            relationMapApi.putEdit(this.form.id, sendData).then(res => {
              if (res.data.success) {
                this.$Message.success({ content: `修改成功`, duration: 3 })
                this.modal1 = false
                this.getList() // 刷新查询列表
                this.form = this.$options.data().form // 初始化form
              } else {
                this.$Message.error(res.data.errorMsg || '服务端错误')
              }
            }).catch(err => {
              console.log(err)
            })
          }
        } else {
          this.$Message.error('请检查表单是否填写完整')
          return false
        }
      })
    }
}

当然你可以这样写,使用try、catch +async、await 推荐一

methods: {
    // 提交表单
    handleSubmit2(name) {
      this.$refs[name].validate(async valid => {
        if (valid) {
          // 提交的数据处理
          let temp = JSON.parse(JSON.stringify(this.form))
          try {
            if (this.modalStatus === 'add') { // 或者也可以this.form.id是否赋值也可以
              delete temp.id // 删不删出看你接口需求,有的接口是不用删除的,这得看后端了
              await relationMapApi.addSyscLogisticsCause(temp)
            } else if (this.modalStatus === 'edit') {
              await relationMapApi.putEdit(temp.id, temp)
            }
            this.$Message.success({ content: `${this.modalStatus === 'edit' ? '更新' : '新增'}成功`, duration: 3 })
            this.modal1 = false
            this.getList() // 刷新查询列表
            this.form = this.$options.data().form // 初始化form
          } catch (err) {
            console.log(err)
            this.$Message.warning(err.data.message)
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
}

当然你也可以写,使用三元表达式和解构语法 推荐二

methods: {
    // 提交表单
    handleSubmit(name) {
      let temp = this.$cloneDeep(this.form2)
      this.$refs[name].validate(async valid => {
        if (valid) {
          // 使用三元表达式判断是哪种类型
          const api = temp.id ? 'putEdit' : 'addSyscLogisticsCause'
          const params = temp.id ? [temp.id, temp] : [temp]
          relationMapApi[api](...params).then(res => { // 解构参数
            if (res.data.success) {
              this.modal1 = false
              this.$Message.success({ content: `${temp.id ? '修改' : '新增'}成功`, duration: 3 })
              this.getList()
              this.form2 = this.$cloneDeep(this.$options.data().form2) // 初始化form
            } else {
              this.$Message.error(res.data.errorMsg || '服务端错误')
            }
          }).catch(err => {
            console.log(err)
          })
        } else {
          this.$Message.error('请检查表单是否填写完整')
          return false
        }
      })
    }
}

上述的推荐一、推荐二你可以参考下,简单而优雅。

还有很多批量操作,当然你也可以这样做,多加个判断就是了,如批量审核,批量开发,批量完成等等,看自己需求而定。