js中this指向问题

fileChange(el) {
      if (!el.target.files[0].size) return;
      // this.fileList(el.target);
      let file = el.target.files[0];
      let oFReader = new FileReader();
      oFReader.readAsDataURL(file);
      oFReader.onload = function(oFREvent) {
        // console.log(oFREvent.target.result); //base64
        this.upImgLUrl = oFREvent.target.result;
      };
      el.target.value = ''
      console.log(this.upImgLUrl);
    },

这里怎么把oFREvent.target.result传出去到全局?
console.log(this.upImgLUrl);打印出来是空

阅读 2.6k
3 个回答

你后边 console.log(this.upImgLUrl);肯定打印不出来的,首先oFReader.onload 你可以把它看做是一个异步事件,在外面直接获取是获取不了onload 里面的赋值的,你可以在onload 里面赋值后调用函数把oFREvent.target.result传给函数,然后在函数里面获取

    function fileChange(el) {
            let file = el.target.files[0];
            let oFReader = new FileReader();
            oFReader.readAsDataURL(file);
            oFReader.onload = function(oFREvent) {
               //console.log(oFREvent.target.result); //base64
              var upImgLUrl = oFREvent.target.result;
                aaa(upImgLUrl);
            };
            el.target.value = '';           
          }
          function aaa(url){
              console.log(url)
          }

改用箭头函数

oFReader.onload = (oFREvent)=> {
    // console.log(oFREvent.target.result); //base64
    this.upImgLUrl = oFREvent.target.result;
  };

异步 外面声明 let that = this

或者简单粗暴 存到sessionStorage里面 外面获取
window.sessionStorage.setItem //存
window.sessionStorage.getItem //获取

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题