1
<div id="app">
<h1> News Aggregator </h1>
<div v-for="CurNews in news">
<div id="title">
<h1>{{CurNews.title}}</h1>
</div>
<div id="description">
<p>{{CurNews.description}}</p>
</div>
</div>
</div>








<script>
const API_KEY = "XXXXXXXXXX";
const url = "https://newsapi.org/v1/articles?";



const app = new Vue({
el: '#app',
data:{
    news: [{
    title:"ABC", description: "VXAEW"
    }]
    },
mounted(){
    axios.get("https://newsapi.org/v1/articles?source=the-times-of-india&sortBy=top&apiKey=XXXXXXXXXXX").then(function(response){
    this.news = response.data.articles;
    //app.$set(this.news, response.data.articles);
    console.log(response.data.articles);
    }).catch(function(error){
    console.log(error);
    })
}
});

</script>

The view does not update. Also, whenever I try to access the response/news object through the console, I get "Reference Error: response/news in not defined". The AJAX call works perfectly.

3 Answers 3

3

In your axios request .then sucess callback this is not pointing to the vue instance since you are using a normal function syntax, use fat arrow => function syntax instead like this:

mounted(){
    axios.get("your URL").then((response) => {
    this.news = response.data.articles;
    console.log(response.data.articles);
    }).catch(function(error){
    console.log(error);
    })
} 

Or else declare a var vm at the start of your mounted block pointing the vue instance like this:

mounted(){
    var vm = this;
    axios.get("your URL").then(function(response) {
    vm.news = response.data.articles;
    console.log(response.data.articles);
    }).catch(function(error){
    console.log(error);
    })
} 
Sign up to request clarification or add additional context in comments.

Comments

0
    <div v-for="CurNews in news">
        <div id="title">
        <h1>{{CurNews.title}}</h1>
    </div>

id is unique, you can use class. The data attribute should be a function.

data(): {
 news: [{
  title:"ABC", description: "VXAEW"
  }]
}

1 Comment

That's not the problem... data must be a function for vue component instances
0

You can try using arrow function like:

fetch("/static/data/data_table.json", {
            method: "GET",
            headers: {
              'Content-Type': 'application/json',
              'Accept': 'application/json'
            }
          }
        )
          .then((response) => {
            return response.json()
          }).then ((json) => {
          this.resultJson = json
        }).catch( (ex) => {
        })

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.