axios 条件参数 [英] Axios conditional parameters

查看:41
本文介绍了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=

Is there any way I can make conditional parameters when doing GET / POST requests with Axios? For example, if my mail parameter is empty, i won't send an empty parameter, like: someurl.com?phone=12312&mail=

推荐答案

或者你可以在发出请求之前维护一个 params 变量,并且只在有如下数据时才添加键:

Either you can maintain a variable of params before making a request and only add key if it has data like:

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

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

or you can do like below, we write normal js code between ...() the parenthesis. We are adding a ternary condition.

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

这篇关于axios 条件参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆