状态未在 onload 函数内分配
state not assigned inside onload function
我正在尝试将图像的数据 url 分配给某个州,但未将其分配给该州。首先,我将一个 blob url 转换为数据 url,然后将其分配给 vuejs 中的一个状态,但是,该状态没有数据 url.
imgSrc 确实显示了 onload 函数内控制台日志的数据 url。但是如果我在任何其他函数中使用状态 imgSrc 那么它会显示 blob url 而不是数据 url.
//suppose I have a blob url and it's passed as a prop
value = blob:http://localhost:8080/ca6d6419-f933-439b-8a16-62a80c81ab1a
upload() {
this.imgSrc = this.value;
let img = new Image();
img.src = this.value;
img.onload = function () {
var canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
canvas.getContext('2d').drawImage(img, 0, 0);
const dataURI = canvas.toDataURL();
this.imgSrc = dataURI;
console.log('imgSrc inside', this.imgSrc); //shows data url
};
console.log('imgSrc outside', this.imgSrc); //shows blob url
},
onload
回调中的 this
不引用 vue 实例,要使其引用你应该将 this
分配给全局变量然后在回调中使用该变量:
upload() {
this.imgSrc = this.value;
let img = new Image();
img.src = this.value;
let vm=this;
img.onload = function () {
var canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
canvas.getContext('2d').drawImage(img, 0, 0);
const dataURI = canvas.toDataURL();
vm.imgSrc = dataURI;
console.log('imgSrc inside', vm.imgSrc);
};
//any code here will be ran before the callback
},
我正在尝试将图像的数据 url 分配给某个州,但未将其分配给该州。首先,我将一个 blob url 转换为数据 url,然后将其分配给 vuejs 中的一个状态,但是,该状态没有数据 url.
imgSrc 确实显示了 onload 函数内控制台日志的数据 url。但是如果我在任何其他函数中使用状态 imgSrc 那么它会显示 blob url 而不是数据 url.
//suppose I have a blob url and it's passed as a prop
value = blob:http://localhost:8080/ca6d6419-f933-439b-8a16-62a80c81ab1a
upload() {
this.imgSrc = this.value;
let img = new Image();
img.src = this.value;
img.onload = function () {
var canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
canvas.getContext('2d').drawImage(img, 0, 0);
const dataURI = canvas.toDataURL();
this.imgSrc = dataURI;
console.log('imgSrc inside', this.imgSrc); //shows data url
};
console.log('imgSrc outside', this.imgSrc); //shows blob url
},
onload
回调中的 this
不引用 vue 实例,要使其引用你应该将 this
分配给全局变量然后在回调中使用该变量:
upload() {
this.imgSrc = this.value;
let img = new Image();
img.src = this.value;
let vm=this;
img.onload = function () {
var canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
canvas.getContext('2d').drawImage(img, 0, 0);
const dataURI = canvas.toDataURL();
vm.imgSrc = dataURI;
console.log('imgSrc inside', vm.imgSrc);
};
//any code here will be ran before the callback
},