[英]Vue.js can't access this (or method return) from component method
我有一個將數據傳遞給方法的組件,但是我需要進一步更改數據,因此我正在嘗試(沒有成功)將其傳遞給函數,但是不管是否將函數放置在方法中,它都無法正常工作或外面。 問題似乎是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')
}
}
},
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')
}
}
},
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.