首页 > 解决方案 > 无法将从 reader.result 获得的字符串分配给变量,返回 null

问题描述

我有以下代码

它在 reader.onload 函数中返回一个字符串,但当我在外部函数中使用 console.log image.Url 时返回 null

编辑:这是完整的代码


export default {
  data() {
    return {
      item: {
        image: null
      },
      imageUrl: null,
    };
  },

  methods: {,
    uploadImage(e) {
      let image = e.target.files[0];
      const reader = new FileReader();
      reader.readAsDataURL(image);

      reader.onload = function(){
        this.imageUrl = reader.result
        console.log(this.imageUrl)
        // this.setImageOne(this.imageUrl)
      }
      console.log(this.imageUrl)
      

    },

编辑:

解决它。感谢大家

标签: javascriptvue.jsscope

解决方案


事情并没有按照你期望的顺序发生。

这是它们发生的顺序:

  1. uploadImage() 调用
  2. 第二个 console.log 运行并且 imageUrl 为空(回调函数为 onload 事件注册)
  3. 运行 onload 回调并设置 imageUrl
 function(){
        this.imageUrl = reader.result
        console.log(this.imageUrl)
        // this.setImageOne(this.imageUrl)
      }

此函数在定义时不运行。Js 只在 onload 事件发生时运行你提供的回调函数。它注册这个回调,然后继续到console.log.

如果你想使用 imageUrl 的值,你应该在回调函数中这样做。


推荐阅读