Vue中使用axios请求后获取this.documentation_data提示undefined如何解决
问题原因
- axios发起的是异步请求,
.then回调只会在接口请求成功后才会执行,你写在.then外部的console.log和后续下载逻辑,会在请求发出后、还没拿到返回结果的时候就执行,此时this.documentation_data还没被赋值,自然是undefined。 - 当前代码还存在变量名冲突问题:函数的入参命名为
response,axios请求成功的回调参数也命名为response,内层变量会覆盖外层变量,可能导致你后续下载逻辑取到的数据源不符合预期。
解决方案1:将依赖请求结果的逻辑移入.then回调
把所有需要用到接口返回数据的代码都放到.then内部,保证执行时已经拿到了返回结果:
forceFileDownload(outerResponse, id) { // 外层参数改名避免冲突 axios.get('/api/documentation/'+ id +'/edit?api_token='+App.apiToken) .then(response => { this.documentation_data = response.data.data; console.log(this.documentation_data); // 移到then内部,此时已经赋值完成 // 如果下载需要用axios返回的data就用当前response.data,如果需要用函数入参的流就替换为outerResponse.data const url = window.URL.createObjectURL(new Blob([response.data])) const link = document.createElement('a') link.href = url link.setAttribute('download', 'movement.pdf') document.body.appendChild(link) link.click() // 用完释放对象优化内存 window.URL.revokeObjectURL(url) document.body.removeChild(link) }); },
解决方案2:用async/await语法改写,逻辑更清晰
async forceFileDownload(outerResponse, id) { try { // await等待请求完成再执行后续逻辑 const response = await axios.get('/api/documentation/'+ id +'/edit?api_token='+App.apiToken) this.documentation_data = response.data.data; console.log(this.documentation_data); const url = window.URL.createObjectURL(new Blob([response.data])) const link = document.createElement('a') link.href = url link.setAttribute('download', 'movement.pdf') document.body.appendChild(link) link.click() window.URL.revokeObjectURL(url) document.body.removeChild(link) } catch (err) { // 这里可以加请求失败的提示逻辑 console.error('请求出错', err) } },
内容的提问来源于stack exchange,提问作者Medicina NA
相关产品推荐
相关产品推荐

