vuejs在模板中呈现异步功能显示promise而不是返回的数据 [英] vuejs rendering async function in template displays promise instead of returned data

查看:238
本文介绍了vuejs在模板中呈现异步功能显示promise而不是返回的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在调用一个异步函数来加载配置文件图片,await调用按预期将值返回到变量"pf",但是我无法从loadProfilePic返回该值.至少在一开始,我试图返回一个静态字符串以在vue模板中显示为 [object Promise] .

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.

但是当我删除await/asnyc时,它虽然返回了字符串.

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']

    },

推荐答案

这是因为 async函数返回了一个本地promise,所以 loadProfilePic 方法实际上返回了一个promise价值.实际上,您可以做的是在 obj 中设置一个空的配置文件图片,然后在您的 loadProfilePic 方法中填充它.当 obj.profilePic 更新时,VueJS将自动重新呈现.

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.com/users/${id}`).then(r => r.json());
    }
  },
  mounted: function() {
    this.obj.forEach(o => this.loadProfilePic(o.id));
  }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <div v-for="i in obj">
    {{ i.profilePic }}
  </div>
</div>

这篇关于vuejs在模板中呈现异步功能显示promise而不是返回的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆