参数为对象时,只传递非空属性至后端
- 发起Ajax请求时,参数可能是对象类型,并且对象包含多个字段。此时,如果后端要求只传递该对象下有值的字段,那么以下方式可生效。
async submit(){
if (!this.hasOne) return
let url = this.$ajaxUrl.rightCenter.space_changeWithdrawalSetting;
let params = {
alipayAccount: this.input_alipay_account || undefined,
cardNo: this.input_bank_account || undefined,
idCard: this.input_idcard || undefined,
name: this.input_name || undefined,
};
let res = await this.https.post(url, params);
if (res.code === '0001'){
return this.$Message.warning(res.msg);
}
if (res.code !== '0000'){
return this.$Message.error(res.msg);
}
this.$Message.success('修改成功');
this.$emit('success');
this.getPayeeInformation();
},
- 假设alipayAccount为空,其他三个属性有值,那么传递到后端的对象如下:
{
cardNo: '哈哈哈',
idCard: '哈哈哈',
name: 'hahaha',
}
{
alipayAccount: null,
cardNo: '哈哈哈',
idCard: '哈哈哈',
name: 'hahaha',
}
JSON.stringify()
方法在序列化对象时针对null
和undefined
的差异
- 通过上面的比较,可以发现
undefined
和null
在某些场景下区别是存在的,虽然在很多场合下,难以区分它们。比如==相等符号就认为二者相等。
// undefined在序列化过程中会被忽略,当然不仅是undefined,也包括函数和Symbol,这里是想强调它和null的差异
JSON.stringify({
foo: 'foo',
bar: null,
foobar: undefined
})
// "{"foo":"foo","bar":null}"
Note
:这里简要总结下二者:null
表示空值,undefined
强调变量未定义、未声明