Vue.js无法从组件方法访问此(或方法返回)

时间:2017-09-14 12:03:51

标签: javascript vue.js

我有一个将数据传递给方法的组件,但我需要进一步更改数据,所以我正在尝试(没有成功)将其传递给一个函数,但它无法正常工作,我是否放置了该函数在方法内或外面。问题似乎是this在任何一种情况下都无法访问,导致undefined警告。

奇怪的是我的第二个方法(photoConvert)被调用(正如我的console.log输出所证明的那样),但数据永远不会返回到调用方法(onChange)。我尝试在数据中设置一个值,尝试只返回值,没有任何效果,它总是显示为undefined

以下是我的方法:

methods: {
photoConvert (file) {
      var f = file 
      var fr = new FileReader()
      fr.readAsDataURL(f) 
      fr.onload = function () {
        var tempImage = new Image()
        tempImage.src = fr.result
        var height = tempImage.height
        var width = tempImage.width
        if (height > 150) { 
          width = width / (height / 150)
          height = 150
        }
        if (width > 150) {
          height = height / (width / 150)
          width = 150
        }
        var c = document.createElement('canvas')
        c.width = width
        c.height = height
        var ctx = c.getContext('2d')
        ctx.drawImage(tempImage, 0, 0, width, height)
        var b64str = c.toDataURL('image/jpeg')
        console.log(b64str) //this outputs correctly, so we know it was called
        this.b64str = b64str //tried setting data element to no effect
        return b64str //never gets to method calling this function
      }
    },
    onChange () {
      if (this.$refs.pictureInput.file) {
        console.log('Picture loaded.') // we got it
        var final64 = this.photoConvert(this.$refs.pictureInput.file)
        console.log(final64) // fails, says undefined
      }
      else {
        console.log('FileReader API not supported')
      }
    }
  },

1 个答案:

答案 0 :(得分:0)

onload是一个异步函数,因此您无法从中返回,您需要使用回调:

methods: {
photoConvert (file, cb) {
      var f = file 
      var fr = new FileReader()
      fr.readAsDataURL(f) 
      fr.onload = function () {
        var tempImage = new Image()
        tempImage.src = fr.result
        var height = tempImage.height
        var width = tempImage.width
        if (height > 150) { 
          width = width / (height / 150)
          height = 150
        }
        if (width > 150) {
          height = height / (width / 150)
          width = 150
        }
        var c = document.createElement('canvas')
        c.width = width
        c.height = height
        var ctx = c.getContext('2d')
        ctx.drawImage(tempImage, 0, 0, width, height)
        var b64str = c.toDataURL('image/jpeg')
        console.log(b64str) //this outputs correctly, so we know it was called
        this.b64str = b64str //tried setting data element to no effect
        cb(b64str) //never gets to method calling this function
      }
    },
    onChange () {
      if (this.$refs.pictureInput.file) {
        console.log('Picture loaded.') // we got it
        this.photoConvert(this.$refs.pictureInput.file, 
         function(final64 ){console.log(final64))

      }
      else {
        console.log('FileReader API not supported')
      }
    }
  },