javascript - 如何在这个 axios Vuejs 中获取变量
问题描述
嗨,我在 Vuejs 中有这段代码:
forceFileDownload(response, id) {
axios.get('/api/documentation/'+ id +'/edit?api_token='+App.apiToken)
.then(response => {
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()
},
我想从上面的 axios 中获取 this.documentation_data,我该怎么做呢?因为它说未定义..并且有数据。
谢谢!
解决方案
此后的代码console.log
不会等待 axios 完成请求,因此它在分配之前执行。 this.documentation_data
您需要将所有代码移动到then
块中,以使其行为符合您的预期。但是,如果这样做,则根本不需要将其分配给documentation_data
变量,您还不如只使用局部变量。
forceFileDownload(response, id) {
axios.get('/api/documentation/'+ id +'/edit?api_token='+App.apiToken)
.then(response => {
console.log(response.data.data); // P.S. Are you sure .data.data is correct here?
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()
});
}
推荐阅读
- java - 确定我的代码是否包含硬编码的 SQL 查询?
- karate - 空手道 + Appium,命令 driver.startRecordingScreen() 不起作用
- java - 计算一个点是否在多边形内
- php - Laravel Wherehas 在枢轴关系中不起作用并且不返回任何数据
- docker - SSH 到 Kubernetes 中的 Sshd docker 服务器会随机返回 exitCode=255
- html - 我想显示我从下拉列表中选择的城市天气信息,我该如何管理它?
- java - Thymeleaf 中的可选参数?
- c# - 什么时候应该使用列表而不是 ICollection 或 IEnumerable?
- android - 如何使用 Kotlin 为 RecyclerView 创建上下文菜单
- phing - Ubuntu 上 phing.php 的权限,以便在 Eclipse 中执行