【问题标题】:variable is populating in vue function but not in template变量填充在 vue 函数中但不在模板中
【发布时间】:2019-08-28 14:59:08
【问题描述】:

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

【问题讨论】:

    标签: vue.js


    【解决方案1】:

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

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

    【讨论】:

    • 已经试过了。还是一样的问题。在控制台中显示数据,但不在模板中
    • @Rafaeatul,您是否尝试先从承诺中删除/评论?
    • 另外,用全功能代替箭头
    • 是的,我做到了。实际上我注意到一些非常有趣的事情,当我转到其他页面并进行缓存清除刷新,然后使用返回箭头返回此页面时,数据正在显示!然后当我刷新页面时,数据又消失了!
    猜你喜欢
    • 2021-08-30
    • 1970-01-01
    • 2017-05-23
    • 2019-03-21
    • 2013-09-12
    • 1970-01-01
    • 2019-06-24
    • 1970-01-01
    • 2021-04-04
    相关资源
    最近更新 更多