问题
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