Rafaeatul
Rafaeatul

Reputation: 43

variable is populating in vue function but not in template

Fetching data from json data in vue function. Then trying to return that in my vue template. It is not returning anything on the template. But in console the variable is showing desired data. For some reason the variable is not working only on the template. I have used this same method to fetch and show data in other places, it worked perfectly. But here is not. It is not even showing any javascript error.

Here is my template:

    <div>
          <ul>
            <li v-for="feed in feeds" v-bind:key="feed.id">
                <h3>{{feed.title}}</h3>
                <p>{{feed.body}}</p>
            </li>
          </ul>
    </div>    

Here is the script:

export default {
data(){
    return {
        feeds: []
    }
},
created(){
    this.fetchFeeds();
},
methods:{
    fetchFeeds(page_url){
        let vm = this;
        page_url= page_url ||'feeds/api'
        fetch(page_url)
        .then(res => res.json())
        .then(res =>{
            this.feeds = res.data;
            console.log(this.feeds); //this showing data in console

        })
        .catch(err => console.log(err));
    }
  }
}

Upvotes: 1

Views: 508

Answers (1)

Nikola Kirincic
Nikola Kirincic

Reputation: 3757

It is the matter of the scope changing this object. When you call fetch() this does not refer to VueJs this object anymore. Just use the vm variable to which you assigned this object.

export default {
data(){
    return {
        feeds: []
    }
},
created(){
    this.fetchFeeds();
},
methods:{
    fetchFeeds(page_url){
        let vm = this;
        page_url= page_url ||'feeds/api'
        fetch(page_url)
       // .then(res => res.json())
        .then(function(res){
            vm.feeds = res.data;
            console.log(vm.feeds); //this showing data in console

        })
        .catch(err => console.log(err));
    }
  }
}

Upvotes: 0

Related Questions