简体   繁体   中英

Preview image before upload VueJs

I try to preview a image before upload, I want to dispaly a small one, and on click to be full size, but till now it didn't work. I am using vue-upload-component , file.thumb from them also didn't work. 在此处输入图片说明

data() {
    return {
        url:null,
    }
}
watch: {
    files: {
        handler: function(){
            this.files.forEach((file,index) =>{
                const file = e.target.file[0];
                this.url = URL.createObjectURL(file);
                console.log('Files:',this.files);
            })
        },
    }
}

//First try found on stack
<div id="preview">
    <img v-if="url" :src="url" />
</div> 

//This is from them , but is not working.
<img v-if="file.thumb" :src="file.thumb" width="40" height="auto" />
<span v-else>No Image</span>

UPDATE Now the small image it works, I just need to add some things form that library. Now I just need to preview full size img hen click.

<img v-if="file.thumb" :src="file.thumb" width="40" height="auto" />

You are using the this from the forEach scope, try initializing the global ViewModel to be able to access the data params, like this :

watch: {
    files: {
        handler: function(){
            let vm = this;
            this.files.forEach((file,index) =>{
                const file = e.target.file[0];
                vm.url = URL.createObjectURL(file);
                console.log('Files:',vm.files);
            })
        },
    }
}

Can you try this?

handler: function(){
  this.files.forEach((file,index) =>{
    const file = event.target.files[0];
    if (file) {
      let reader = new FileReader();
        reader.onload = (e: any) => {
          this.url = e.target.result; //Base64 string
        }
    }
  })
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM