Vue.js使用Axios传递多个id参数出现数组后缀问题如何解决?
问题原因
该现象是axios默认的参数序列化规则导致的:传递数组类型的查询参数时,默认会给参数名加上[]后缀,就会出现你看到的ids[]=123&ids[]=245格式。
解决方案
方案1:通过paramsSerializer配置修改序列化规则(推荐)
axios本身依赖qs库,无需额外安装,只需在请求配置中指定数组序列化格式为repeat,就能生成你期望的ids=123&ids=245格式。
修改后的代码如下:
import qs from 'qs' const postRes = await axios.post('employee/departments', this.details); const getRes = await axios.get('employee/departments', { params: { ids: postRes.map(i=>i.id)}, // 新增参数序列化配置 paramsSerializer: (params) => { return qs.stringify(params, { arrayFormat: 'repeat' }) } }, ); this.$emit('fileDetails', getRes.data);
如果项目所有请求都需要这种数组参数格式,也可以直接做全局配置:
import qs from 'qs' axios.defaults.paramsSerializer = (params) => { return qs.stringify(params, { arrayFormat: 'repeat' }) }
方案2:手动拼接查询参数
如果不想修改序列化配置,也可以手动拼接符合要求的参数串:
const postRes = await axios.post('employee/departments', this.details); const idList = postRes.map(i=>i.id) // 手动拼接参数 const paramsStr = idList.map(id => `ids=${encodeURIComponent(id)}`).join('&') const getRes = await axios.get(`employee/departments?${paramsStr}`); this.$emit('fileDetails', getRes.data);
内容的提问来源于stack exchange,提问作者user2410266
相关产品推荐
相关产品推荐

