javascript - 无法将从 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)
},
编辑:
解决它。感谢大家
解决方案
事情并没有按照你期望的顺序发生。
这是它们发生的顺序:
- uploadImage() 调用
- 第二个 console.log 运行并且 imageUrl 为空(回调函数为 onload 事件注册)
- 运行 onload 回调并设置 imageUrl
function(){
this.imageUrl = reader.result
console.log(this.imageUrl)
// this.setImageOne(this.imageUrl)
}
此函数在定义时不运行。Js 只在 onload 事件发生时运行你提供的回调函数。它注册这个回调,然后继续到console.log
.
如果你想使用 imageUrl 的值,你应该在回调函数中这样做。
推荐阅读
- reverse-proxy - 使用 Traefik 的反向代理:如何在 URL mydom.com/subfolder01 和 mydom.com/subfolder02 中路由子文件夹
- javascript - javascript中switch语句中预期的声明或语句
- c++ - Xcode - 终端程序的 C++ 代码将无法运行
- javascript - 多人连接onicecandidate事件不会触发
- python - 使用 Pulp 进行线性规划 - 约束分配
- c - 如何使用 CMake 复制现代 IDE 的“构建和运行”功能?
- wordpress - 开发网站时如何将 Figma 中的 px 比例转换为实际屏幕尺寸
- laravel - 在控制器内模拟服务类
- vb.net - 如何在 Visual Basic 中正确添加十六进制数字?
- sql - 标准sql中的复合百分比