Image not showing on loop using :ref
I am using FileReader() to read the field.
Vue Component
<div v-for="(image, index) in imgFile" :key="index">
<img :ref="'image'+parseInt( index )">
{{image.name}}
</div>
<input type="file" class="file-upload-default" @change="onFileChange" multiple>
<span style="cursor:pointer" class="file-upload-browse">
<img src="/addmore.png" height="50" width="50">
</span>
export default{
onFileChange(e){
var selectedFiles = e.target.files;
for (var i=0; i < selectedFiles.length; i++){
this.imgFile.push(selectedFiles[i]);
}
if (selectedFiles) {
for (var i=0; i < this.imgFile.length; i++){
let reader = new FileReader();
reader.addEventListener('load', function(){
this.$ref["image"+parseInt( i )][0].src = reader.result;
}.bind(this), false);
reader.readAsDataURL(this.imgFile[i]);
}
}
}
}
I want to show the images which is selected from eventListener.
Improve your architecture by splitting your logic into two components. You can do this like this:
<template>
<div class="parent-component">
<image-component :image="image" v-for="(image, index) in images" :key="index" />
</div>
</template>
<script>
export default {
name: 'ParentComponent',
data () {
return {
images: []
};
}
};
</script>
<template>
<div class="image-component">
<img ref="imgElement">
{{ image.name }}
</div>
</template>
<script>
export default {
name: 'ChildComponent',
props: {
image: {
type: Object,
required: true
}
},
methods: {
...
},
mounted () {
// you don't have to loop here, because in the scope of the image-component,
// you only have one `<img>`-tag. the loop is in the parent component
console.log(this.$refs.imgElement);
}
};
</script>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.