变量正在vue函数中填充,但不在模板中

时间:2019-04-07 08:00:45

标签: vue.js

在vue函数中从json数据中获取数据。然后尝试在我的vue模板中返回该值。它不会在模板上返回任何内容。但是在控制台中,变量显示所需的数据。由于某种原因,该变量仅在模板上不起作用。 我使用了相同的方法来在其他地方获取和显示数据,它工作得很好。但是这里不是。 它甚至没有显示任何JavaScript错误。

这是我的模板:

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

这是脚本:

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));
    }
  }
}

1 个答案:

答案 0 :(得分:0)

这是范围更改this对象的问题。 当您调用fetch()this时,不再引用VueJs this对象。 只需使用为您分配了vm对象的this变量即可。

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));
    }
  }
}