Vuejs。我无法将数据传输到对象

时间:2019-02-07 14:28:33

标签: vue.js

我想在FilePond中捕获上载的文件。但是文件的base64不会传输到我的对象。有解决方案吗?

在模板中

    <FilePond
   v-on:addfile="catch"
    />

数据中

  data:function() {
        return {
    image:'',
   }}

方法中

catch: function(fieldName, file) {
    console.log('#', file.file) // The Blop format file appears in console

    const reader = new FileReader(); //convert to base64
    reader.readAsDataURL(file.file); 
    reader.onloadend = function() {

   console.log('yy',reader.result); // Base64 image appears in console 
   (600000 carac)
    this.image= reader.result ; // HERE, the object still blank

    } },

控制台错误:

Uncaught TypeError: Cannot set property 'image' of undefined
at FileReader.reader.onloadend 

1 个答案:

答案 0 :(得分:1)

this关键字被onloadend函数遮盖,在定义该函数之前保存this,然后在内部引用它:

methods: {
  catch: function(fieldName, file) {
    // ...
    var ref = this
    reader.onloadend = function() {
      ref.image= reader.result   // use ref here
    }
    // ...
  }
}