简体   繁体   中英

How to assign array fetched from an API to data property in Vue.js?

I am trying to fetch news articles from an external source, it returns JSON object. I want to assign its articles property to a variable in my component. Somehow this error is occurring.

Uncaught (in promise) TypeError: Cannot set property 'articles' of undefined

Any suggestions on how to overcome this problem?

export default {
  name: "blog",
  data() {
    return {
      articles: [],
    };
  },
  mounted() {
    // API call
    this.fetchnews();
  },
  methods: {
    fetchnews(){
      fetch(
      "----------------------news link-------------------------"
    )
      .then(function(response) {
        return response.json();
      })
      .then(function(json_data) {
        //console.log(typeof(json_data))
        this.articles = json_data.articles
      });
    }
  }
};

As the first contributor properly noticed - the issue is this.articles inside your latest function doesn't really point to what you need. If you are limited to ES5 then stick to the first answer. However if you can use ES6 then simply get advantages of short syntax:

export default {
  name: "blog",
  data() {
    return {
      articles: [],
    };
  },
  mounted() {
    // API call
    this.fetchnews();
  },
  methods: {
    fetchnews(){
      fetch("----------------------news link-------------------------")
      .then(response => response.json())
      .then(json_data => this.articles = json_data.articles);
    }
  }
};
  • in this case this will properly point to the outer scope.

Also why do you need two then() ? You could collapse them into one:

.then(response => this.articles = response.json().articles);

in this.articles : here this refers to the function not vue instance , so you may define this outside the function like:

let This=this

and inside your function :

This.articles = json_data.articles This here refers to vue instance

using function keyword creates new scope. if you use arrow syntax like () => {} you can use parent scope and set articles via this.articles

fetchnews(){
  fetch()
  .then((response) => {
    return response.json();
  })
  .then((json_data) => {
    this.articles = json_data.articles
  });
}

javascript function作为全局范围确保用于将函数分配给变量

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM