首页 > 解决方案 > 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 个包含数据的对象和一个没有数据的对象。但是,那个没有数据的对象突然消失了。

标签: vue.jsvuejs2vue-component

解决方案


Axios 是一个异步调用,因此似乎在 fetch 调用返回之前调用了 console.log。最方便的使用 axios 的方式是用 es2017 async/await 调用它。


推荐阅读