vuejs 2组件base64图像未更新
what i want to achieve:
load an image from jwt token protected source
the server return the image as base64 string and i'll load this string as background url on the image
parent component:
<template lang="html">
<myImage v-for="photo in form.photos" :photo="photo" @delphoto="deleteImage"></myImage>
</template>
export default {
components: {
myImage,
},
data(){
return {
form: {
photos: [
{
id: 1,
thumbnail: "logo1.png"
},
{
id: 2,
thumbnail: "logo2.png"
},
{
id: 3,
thumbnail: "logo3.png"
},
{
id: 4,
thumbnail: "logo4.png"
},
]
},
}
},
methods: {
deleteImage(myphoto)
{
this.form.photos.splice(this.form.photos.indexOf(myphoto), 1);
}
}
}
myImage component
<template>
<div v-if="loaded" class="img">
<img class="albumimg" :style="{ background: img}" :title="title">
<p @click="delimage">delete</p>
</div>
<div v-else class="img">
<img class="loading" style="background: url('/images/spinner.gif')">
</div>
</template>
<script>
export default {
data(){
return {
img: null,
loaded: false
}
},
props: {
photo: {
required: true
},
title: {
default: ''
},
},
created() {
this.imgurl()
},
methods: {
delimage() {
this.$emit('delphoto', this.photo)
},
imgurl() {
this.$http.get("/api/images/" + this.photo.id).then(response => {
this.img = "url('" + response.data + "')"
this.loaded = true
}, response => {
});
},
}
}
</script>
now if i delete a photo (splice) from the form.photos array always the last image get removed. when i remove the green image
the blue image disappears
when i check the form.photos array, the correct image was removed, only the img data attribute from myImage component is still the old value from the previous array position 1.
i was able to bypass this issue by adding a watch on the photo prop and refetch the base64 string which cause a new get request for every image
watch: {
photo: function (val) {
this.imgurl()
}
},
is there any way to remove an array item (child component) and display the correct result without fetching all images again within the child component?
thanks
解决方案Try this.
<myImage v-for="photo in form.photos" :key="photo.id" :photo="photo" @delphoto="deleteImage"></myImage>
From the current documentation.
In 2.2.0+, when using v-for with a component, a key is now required.
相关文章