[Vuejs]-Vue.js can't access this (or method return) from component method

0👍

onload is an async function so you can’t return from it, you need to use a callback:

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')
      }
    }
  },

Leave a comment