首页 > 解决方案 > 带有 CryptoJS 的 VueJS 哈希文件

问题描述

我正在与您联系,因为我非常坚持 Vue 项目......

尝试将 jQuery 项目移至 Vue 时遇到一个小问题。CryptoJS 很有魅力,我可以从字符串创建散列。

但是,我仍在努力阅读实际文件,因为嵌套函数会引发错误。callbackRead特别是在函数上出现错误。

App.vue?234e:280 Uncaught TypeError: this.callbackRead is not a function
at FileReader.reader.onload (App.vue?234e:280)

你能给我一些关于如何成功地将脚本翻译成 VUE JS 的指导吗?( https://medium.com/@0xVaccaro/hashing-big-file-with-filereader-js-e0a5c898fc98 )

非常感谢提前!!!

这是我到目前为止得到的:https ://codesandbox.io/s/vuejs-file-crypter-kjirp

最好的问候,麦克

标签: javascriptvue.jsvuejs2cryptojs

解决方案


错误来自此部分:

reader.onload = function(evt) {
    this.callbackRead(this, file, evt, callbackProgress, callbackFinal);
};

问题是this指错了对象。您的onload处理程序是与周围代码不同的函数,每当您输入新函数时,值都会发生this变化。

有几种可能的解决方案。

别名this

const that = this;

reader.onload = function(evt) {
    that.callbackRead(that, file, evt, callbackProgress, callbackFinal);
};

绑定this

reader.onload = function(evt) {
    this.callbackRead(this, file, evt, callbackProgress, callbackFinal);
}.bind(this);

使用箭头函数,它不会改变 的值this

reader.onload = evt => {
    this.callbackRead(this, file, evt, callbackProgress, callbackFinal);
};

推荐阅读