vue.js - Vue 方法在其他方法中使用时返回 undefined
问题描述
我正在尝试获取对象中评论的回复。从后端,即 LARAVEL,我收到 1 个对象。但是,在 Vue 中它变得未定义
方法
fetchReplies(commentid) {
axios
.get("/reply/" + commentid)
.then(res => {
if (res.data != null) {
console.log(res.data);
return res.data;
}
})
.catch(function(err) {
console.log(err);
});
}
输出
(2) [{…}, {…}] // 用于注释 42
但是当在其他方法中使用这种方法时
fetchComments() {
var boardid = this.boardid;
axios
.get("/comment/" + boardid)
.then(res => {
if (res.data != null) {
this.comments = res.data;
console.log(this.fetchReplies(42));
}
})
.catch(function(err) {
console.log(err);
});
},
输出
不明确的
不久之前,当我在 Vue 中获取时,我收到 1 个包含数据的对象和一个没有数据的对象。但是,那个没有数据的对象突然消失了。
解决方案
Axios 是一个异步调用,因此似乎在 fetch 调用返回之前调用了 console.log。最方便的使用 axios 的方式是用 es2017 async/await 调用它。
推荐阅读
- function - 用同一个合约中的另一个函数在solidity中调用一个公共函数
- javascript - 为什么来自 Europeana API 响应的 json 对象的 if/else 检查不一致?
- javascript - 刷新后如何保持在jquery DataTable的同一页面上?
- vba - VBA = 如何提取新工作簿中的特定行?
- pdf - 如何:使用 Google pdf 查看器定位 pdf 文件中的书签?网址格式
- linux - 在dietpi中设置hostap但未找到错误
- css - 为特定 Route 向 Header 组件添加样式
- javascript - whatsapp-web.js 如何保存 downloadMedia()
- database - 如何使用 Redis 从大型数据集中获取数据?
- php - PHP - 环境变量只能在浏览器中使用,不能在命令行中使用