最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - vuejs rendering async function in template displays promise instead of returned data - Stack Overflow

programmeradmin4浏览0评论

I am calling an async function which loads the profile pic, the await call returns the value to the variable 'pf' as expected, but I couldn't return that from loadProfilePic. At least for the start I tried to return a static string to be displayed as [object Promise] in vue template.

But when I remove await/asnyc it returns the string though.

<div  v-for="i in obj">
              {{ loadProfilePic(i.id) }}
</div>

   loadProfilePic: async function(id) {
           var pf = await this.blockstack.lookupProfile(id)
           return 'test data';
           //return pf.image[0]['contentUrl']

    },

I am calling an async function which loads the profile pic, the await call returns the value to the variable 'pf' as expected, but I couldn't return that from loadProfilePic. At least for the start I tried to return a static string to be displayed as [object Promise] in vue template.

But when I remove await/asnyc it returns the string though.

<div  v-for="i in obj">
              {{ loadProfilePic(i.id) }}
</div>

   loadProfilePic: async function(id) {
           var pf = await this.blockstack.lookupProfile(id)
           return 'test data';
           //return pf.image[0]['contentUrl']

    },
Share Improve this question asked Mar 1, 2019 at 8:25 Code TreeCode Tree 2,2094 gold badges28 silver badges40 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 12

That is because async function returns a native promise, so the loadProfilePic method actually returns a promise instead of a value. What you can do instead, is actually set an empty profile pic in obj, and then populate it in your loadProfilePic method. VueJS will automatically re-render when the obj.profilePic is updated.

<div  v-for="i in obj">
    {{ i.profilePic }}
</div>

loadProfilePic: async function(id) {
   var pf = await this.blockstack.lookupProfile(id);

   this.obj.filter(o => o.id).forEach(o => o.profilePic = pf);
}

See proof-of-concept below:

new Vue({
  el: '#app',
  data: {
    obj: [{
      id: 1,
      profilePic: null
    },
    {
      id: 2,
      profilePic: null
    },
    {
      id: 3,
      profilePic: null
    }]
  },
  methods: {
    loadProfilePic: async function(id) {
      var pf = await this.dummyFetch(id);
      this.obj.filter(o => o.id === id).forEach(o => o.profilePic = pf.name);
    },
    dummyFetch: async function(id) {
      return await fetch(`https://jsonplaceholder.typicode./users/${id}`).then(r => r.json());
    }
  },
  mounted: function() {
    this.obj.forEach(o => this.loadProfilePic(o.id));
  }
});
<script src="https://cdnjs.cloudflare./ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <div v-for="i in obj">
    {{ i.profilePic }}
  </div>
</div>

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论