【问题标题】:state not assigned inside onload function状态未在 onload 函数内分配
【发布时间】:2021-10-14 00:34:14
【问题描述】:

我正在尝试将图像的数据 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
    },

【问题讨论】:

    标签: javascript vue.js vuejs2 blob vuejs3


    【解决方案1】:

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

    【讨论】:

    • 哦,哇,我不知道这个。非常感谢
    • 顺便说一句,为什么this 没有引用到 vue 实例?
    • 不客气,因为它指的是 onload 回调的上下文
    猜你喜欢
    • 2016-05-28
    • 2014-10-23
    • 2013-10-31
    • 1970-01-01
    • 2013-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多