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=
您可以在发出请求之前维护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 } : {})
},
})
Raghav Garg的想法乍一看看起来很整洁,但是有一个以上的可选参数,我担心它会变得混乱。
你可以简单地使用一个常见的实用程序库,如下划线或lodash,并使用他们的filter
函数:
const allParams = {
mail: this.mail,
phone: this.phone,
// ...
};
axios.get(globalConfig.FAKE_API, {
// 'Pick' takes only those elements from the object
// for which the callback function returns true
//
// Double negation will convert any value to its boolean value,
// so null becomes false etc.
params: _.pick(allParams, (value, key) => { return !!value; })
})