状态未在 onload 函数内分配 [英] state not assigned inside onload function

查看:26
本文介绍了状态未在 onload 函数内分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将图像的数据 url 分配给某个状态,但未将其分配给该状态.首先我将一个blob url转换为数据url,然后将其分配给vuejs中的一个状态,但是,该状态没有数据url.

I'm trying to assign the data url of an image to a state but it isn't being assigned to the state. First I convert a blob url to data url and then assign it to a state in vuejs, however, the state doesn't have the data url.

imgSrc 确实在 onload 函数中显示了控制台日志的数据 url.但是如果我在任何其他函数中使用状态 imgSrc 那么它会显示 blob url 而不是数据 url.

The imgSrc does show the data url for the console log inside the onload function. but if I use the state imgSrc in any other function then it shows the blob url instead of the data 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
    },

推荐答案

thisonload 回调中不引用 vue 实例,让它引用你应该将 this 分配给一个全局变量,然后在回调中使用该变量:

this inside the onload callback doesn't refer to the vue instance , to make it refer you should assign this to a global variable then use that variable inside the callback :

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

这篇关于状态未在 onload 函数内分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆