【问题标题】:bind base64 string to src image is not working with vue将 base64 字符串绑定到 src 图像不适用于 vue
【发布时间】:2019-05-24 02:46:40
【问题描述】:

我正在尝试将 base64 数据绑定到 img 属性的 src。在将新值设置为 img vue 属性之前,代码工作正常

我构建了这个

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>

不起作用,base64 设置正常,但未渲染到图像。

我的代码有什么问题?

【问题讨论】:

    标签: javascript vue.js


    【解决方案1】:

    this 上下文在 reader.onload 内部发生了变化。

    只需将this 存储在这样的临时变量中:

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

    例子:

    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>

    【讨论】:

    • 很棒的老师。它也可以作为 reader.onload = () =&gt; { ... } 工作,并且不需要创建 const。很棒的方向兄弟 tnx
    猜你喜欢
    • 2020-12-18
    • 2019-08-04
    • 2019-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多