在进行请求操作是,往往会定义一个params请求体进行传参,有的时候需要请求体参数是一个变量,之前百度和CSDN上找了很多blog,也没找到合适的解决办法,自己尝试了很多种方法,最终使用下面这种方法解决了:
下面是一个confirm提交请求,下面的请求体params中,想让第二个对象的变量名随着sub_type的变化而变化:
// 参数设置private ruleForm: any = { base_type: '', sub_type: '', name: '', version: '' };1234567
// 错误示范:private confirm(): void { this.formRef.validate((valid: boolean) => { if (valid) { let sub_type_info = this.ruleForm.sub_type+ '_info'; let params = { base_info: { base_type: this.ruleForm.base_type, sub_type: this.ruleForm.sub_type }, sub_type_info : { name: this.ruleForm.name, version: this.ruleForm.version } }; this.configForm(params); } else { this.$message({ type: 'error', message: '请输入正确的表单数据' }); }; }); } // 请求体为: { base_info: { base_type: 'text', sub_type: 'text' }, sub_type_info : { name: 'text', version: 'text' } } 12345678910111213141516171819202122232425262728293031
// 正确示范:private confirm(): void { this.formRef.validate((valid: boolean) => { if (valid) { let params = { base_info: { base_type: this.ruleForm.base_type, sub_type: this.ruleForm.sub_type }, [this.ruleForm.sub_type+ '_info']: { name: this.ruleForm.name, version: this.ruleForm.version } }; this.configForm(params); } else { this.$message({ type: 'error', message: '请输入正确的表单数据' }); }; }); } // 请求体为: { base_info: { base_type: 'text', sub_type: 'text' }, text_info : { name: 'text', version: 'text' } } 123456789101112131415161718192021222324252627282930
从上面的事例可以看到,第一个传参是sub_type_info ,没有随参数改变而改变;第二个传参是text_info ,随着sub_type的变化而变化,达到了需求。
总结:传参时需要将变量名用中括号括起来,才可以识别为一个变量,否则设置什么就会以什么为变量名去传参。
作者:SmallTeddy
链接:https://blog.csdn.net/SmallTeddy/article/details/107375506
来源:CSDN
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。