vue。js json对象数组作为数据

时间:2023-02-06 21:15:33

aye folks!

赞成的人!

I'm currently learning to do stuff with vue.js. unfortunately i'm stuck atm. what i want to do is sending a request to my sample API which responds with a simple json formatted object. I want to have this object as data in my component – but it doesn't seem to do that for whatever reason.

我目前正在学习使用vue.j。不幸的是我被atm。我要做的是向示例API发送一个请求,该API用一个简单的json格式的对象进行响应。我想让这个对象在我的组件中作为数据-但是它似乎没有因为任何原因那样做。

Ofc i tried to find a solution on * but maybe i'm just blind or this is just like the code other people wrote. i even found this example on the official vue website but they're doing the same thing as i do .. i guess?

Ofc我试着在*上找到一个解决方案,但是也许我只是瞎了,或者这就像其他人写的代码一样。我甚至在官方的vue网站上找到了这个例子,但是他们和我做的是一样的。我猜?

btw. When i run the fetchData() function in a separate file it does work and i can access the data i got from my API. no changes in the code .. just no vue around it. i'm really confused right now because i don't know what the mistake is.

顺便说一句。当我在一个单独的文件中运行fetchData()函数时,它确实可以工作,我可以访问从API中获得的数据。代码没有变化。只是周围没有人。我现在很困惑,因为我不知道错在哪里。

code:

代码:

var $persons = [];

and inside my component:

和在我的组件:

data: {

  persons: $persons,
  currentPerson: '',
  modal: false

},


created: function() {

  this.fetchData()

},


methods: {

  fetchData: function () {

    var ajax = new XMLHttpRequest()

    ajax.open('GET', 'http://api.unseen.ninja/data/index.php')
    ajax.onload = function() {
      $persons = JSON.parse(ajax.responseText)
      console.log($persons[0].fname)
    }
    ajax.send()

  }

},

[...]

link to the complete code

链接到完整的代码

1 个解决方案

#1


2  

First, make sure that the onload callback is actually firing. If the GET request causes an error, onload won't fire. (In your case, the error is CORS-related, see this post suggested by @Pradeepb).

首先,确保onload回调实际上是被激活的。如果GET请求导致错误,onload将不会启动。(在您的例子中,错误与cors相关,请参见@Pradeepb建议的这篇文章)。

Second, you need to reference the persons data property directly, not the $persons array that you initialized persons with.

其次,您需要直接引用person数据属性,而不是初始化person的$persons数组。

It would look like this (inside your fetchData method):

它看起来像这样(在fetchData方法中):

var self = this;
ajax.onload = function() {
  self.persons = JSON.parse(ajax.responseText)
  console.log($persons[0].fname)
}

#1


2  

First, make sure that the onload callback is actually firing. If the GET request causes an error, onload won't fire. (In your case, the error is CORS-related, see this post suggested by @Pradeepb).

首先,确保onload回调实际上是被激活的。如果GET请求导致错误,onload将不会启动。(在您的例子中,错误与cors相关,请参见@Pradeepb建议的这篇文章)。

Second, you need to reference the persons data property directly, not the $persons array that you initialized persons with.

其次,您需要直接引用person数据属性,而不是初始化person的$persons数组。

It would look like this (inside your fetchData method):

它看起来像这样(在fetchData方法中):

var self = this;
ajax.onload = function() {
  self.persons = JSON.parse(ajax.responseText)
  console.log($persons[0].fname)
}