首页 > 解决方案 > axios 条件参数

问题描述

axios.get(globalConfig.FAKE_API, {
    params: {
        phone: this.phone,
        mail: this.mail
    },
})
.then((resp) => {
    this.req = resp.data
 })
.catch((err) => {
     console.log(err)
 })

使用 Axios 进行 GET / POST 请求时,有什么方法可以制作条件参数?例如,如果我的mail参数为空,我不会发送空参数,例如:someurl.com?phone=12312&mail=

标签: javascriptaxios

解决方案


您可以params在发出请求之前维护一个变量,并且仅在它具有以下数据时才添加密钥:

const params = {}
if (this.mail) { params.mail = this.mail }

或者你可以像下面这样,我们...()在括号之间写普通的js代码。我们正在添加一个三元条件。

axios.get(globalConfig.FAKE_API, {
  params: {
    phone: this.phone,
    ...(this.mail ? { mail: this.mail } : {})
  },
})

推荐阅读