您如何生成Blob URL? [英] How do you generate a blob URL?

查看:532
本文介绍了您如何生成Blob URL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将imgsrc设置为vuejs中的Blob URL.

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

我试图在imgsrc内调用loadImg()方法;没用这是我的代码:

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

}

如何将图像src设置为Blob网址? codesandbox => https://codesandbox.io/embed/2vmwj2k550

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

推荐答案

如注释中所述,您确实不想在这里使用方法.一方面,它们在注入内容时效率很低.

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.

例如

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

并在您的模板中

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

这篇关于您如何生成Blob URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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