vue 踩坑日志之 FileReader 无法抛出值

  问题:

         在vue 中我上传文件后试图通过reader.readAsText(file)来读取文本内容,结果在reader.onload() 中能够正常显示,但是将之抛给外部变量时,却无法读取到。

            handleFileChange(file) {
                const reader = new FileReader();
                reader.readAsText(file)
                reader.onload = () => {
                    this.file = reader.result;
                };
                console.log(this.file)  // 不显示reader 值
            },

 

  原因:

         reader.readAsText(file) 需要时间读取 此处产生了异步,使得传参赋值还未完成故外部的变量值未得到修改。

  解决方法一(错误):

             通过setTimeout() 形式等待this.file 得到处理。

              结果。。。。。。 整个程序都停止,没有任何变化 。

解决方法二(正确):

        采用reader.onloadend() = () => {} 回调函数,即等readAsText()完成后进行以下操作。

            handleFileChange(file) {
                const reader = new FileReader();
                reader.readAsText(file)
                reader.onloadend = () => {
                    this.file = reader.result;
                };
                console.log(typeof this.file) // String 
            },

                 

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值