使用:ref
时图像未循环显示我正在使用FileReader()来读取字段。
Vue组件
<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]);
}
}
}
}
我想显示从事件监听器中选择的图像。
答案 0 :(得分:0)
通过将逻辑分为两个部分来改善您的体系结构。您可以这样:
<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>