如何仅在加载数据后才能访问数据?

How to get access to data only after they are loaded?

我有 Vue.extend:

data: function ()  {
  return {
     questions: []
  }

  },
  ready() 
  { 
    this.getQuestionsContent(),
    this.foo()
  },
  methods: 
  {

     getQuestionsContent()
     {
        this.$http.get('http://127.0.0.1:8080/js/questions.json').then(function(response)
        {
          this.questions = response.data;

        }); 

      },
      foo()
      {
        console.log(this.$get('questions'));
      }

  }

getQuestionsContent 检索内容。但是当我尝试使用 console.log(this.$get('questions')); 在 Chrome 控制台上打印它时,我只看到空对象。用 console.log 打印时似乎没有加载它。我该如何解决?

尝试使用异步函数。也许是这样的:

this.getQuestionsContent(function(questions) {
    console.log(questions);
})

getQuestionsContent(callback) {
    this.$http.get('http://127.0.0.1:8080/js/questions.json').then(function(response)
    {
        callback(response.data);
    }); 
}

只有当您从服务器获得响应时才会调用回调函数。

您的回调函数 运行 不在您的 vue 组件的范围内。您需要将 this 绑定到该函数,以便您可以设置 this.questions:

this.$http.get('http://127.0.0.1:8080/js/questions.json').then(function(response)
    {
      this.questions = response.data;

    }.bind(this)); 

在异步请求的回调函数之前,您将无法访问问题。因此在发送请求后立即调用 this.foo() 永远不会显示数据。