【发布时间】:2018-02-23 09:50:46
【问题描述】:
我有一个将数据传递给方法的组件,但我需要进一步更改数据,所以我尝试(没有成功)将其传递给函数,但无论我放置函数,它都不起作用在方法内部或外部。问题似乎是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')
}
}
},
【问题讨论】:
标签: javascript vue.js