0

I´m trying to bind base64 data to src of img property. The code works fine until set the new value to the img vue property

I build this

new Vue({

el: '#app',
data: {
  img: ''
},

methods: {
  upload: function( event ){
    let file = event.target.files[0];
				if( !file ) {
					return;
				} else {
					let imageType = /image.*/;
					if ( !file.type.match( imageType ) ) {
						return;	
					} else {
						let reader = new FileReader();

						reader.onload = function( e ) {
							this.img = reader.result;
						}

						reader.readAsDataURL(file);
					}
				}
  }
}

})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  
  <img :src="img" width="200" height="200" />
  <input type="file" @change="upload">
</div>

Is not working, the base64 is set OK, but is not rendered to the image.

What is wrong with my code?

1 Answer 1

4

The this context is changed inside of reader.onload.

Just store this inside a temporary variable like this:

[...]
const that = this;
reader.onload = function( e ) {
    that.img = reader.result;
}
[...]

Example:

new Vue({

el: '#app',
data: {
  img: ''
},

methods: {
  upload: function( event ){
    let file = event.target.files[0];
				if( !file ) {
					return;
				} else {
					let imageType = /image.*/;
					if ( !file.type.match( imageType ) ) {
						return;	
					} else {
						let reader = new FileReader();

						const that = this;
						reader.onload = function( e ) {
							that.img = reader.result;
						}

						reader.readAsDataURL(file);
					}
				}
  }
}

})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  
  <img :src="img" width="200" height="200" />
  <input type="file" @change="upload">
</div>

Sign up to request clarification or add additional context in comments.

1 Comment

awesome sensei. It works too as reader.onload = () => { ... } and is not neccesary to create the const. Awesome orientation bro tnx

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.