How do you generate a blob URL?

只谈情不闲聊 提交于 2020-07-23 10:00:28

问题


I'm trying to set the img and src to blob URL in vuejs.

I have tried to call loadImg() method inside img and src; It didn't work. Here is my code:

<template>
 <a v-for="(post,index) in posts" :key="index">
     <img :src="loadImg(post.img)" >
 </a>
</template>

methods:{

loadImg: function (img) {

        fetch(img)
         .then(function(t){return t.blob()})
         .then(function(e){
          return URL.createObjectURL(e);
        }
      )
 }

}

How do I set the image src to blob url? codesandbox => https://codesandbox.io/embed/2vmwj2k550


回答1:


As mentioned in the comments, you really don't want to use a method here. For one, they are highly inefficient when used to inject content.

What you want to do instead is load the images asynchronously and handle the various states.

For example

data () {
  return { posts: [/* your data goes here */] } // initial data
},
async created () {
  for (let post of posts) { // using for..of so async actually waits
    // create some nice placeholder images to show something while they load
    // including the placeholder would probably work better in your initial data
    this.$set(post, 'imgUrl', 'some-nice-placeholder-image.png')

    // now load the images
    post.imgUrl = URL.createObjectURL(await fetch(post.img).then(res => res.blob()))
  }
},
beforeDestroy() {
  // cleanup
  this.posts.forEach(({ imgUrl }) => {
    URL.revokeObjectURL(imgUrl)
  })
}

and in your template

<a v-for="(post,index) in posts" :key="index">
  <img :src="post.imgUrl" >
</a>


来源:https://stackoverflow.com/questions/55565170/how-do-you-generate-a-blob-url

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!