1.采用的是element上传组件,action必写
<el-upload action="/" ref="upload" accept=".json" :before-upload="beforeUpload" :disabled="this.fileList.length !== 0" :default-file-list="this.fileList">
<el-button type="primary" :disabled="this.fileList.length !== 0">上传文件</el-button>
</el-upload>
2.读取上传的组件的文本,根据自己的需要可以转换成对象JSON.parse(str)
beforeCreate() {
// 读取文件
FileReader.prototype.reading = function ({encode} = pms) {
let bytes = new Uint8Array(this.result); //无符号整型数组
let text = new TextDecoder(encode || 'UTF-8').decode(bytes);
return text;
};
/* 重写readAsBinaryString函数 */
FileReader.prototype.readAsBinaryString = function (f) {
if (!this.onload) //如果this未重写onload函数,则创建一个公共处理方式
this.onload = e => { //在this.onload函数中,完成公共处理
let rs = this.reading();
console.log(rs);
};
this.readAsArrayBuffer(f); //内部会回调this.onload方法
};
},
methods:{
beforeUpload(file){
this.fileList = [file]
console.log('选择了文件beforeUpload')
// 读取数据
this.read(file);
return false
},
read(f) {
let rd = new FileReader();
rd.onload = e => {
//this.readAsArrayBuffer函数内,会回调this.onload函数。在这里处理结果
let cont = rd.reading({encode: 'GBK'});//如果有中文采用UTF-8
console.log(cont);
let formerData = this.textData;
this.textData = formerData + "\n" + cont;
};
rd.readAsBinaryString(f);
}
}
3.安装json比对npm install --save vue-json-compare
<div>
<vue-json-compare :oldData="oldData" :newData="newData"></vue-json-compare>
</div>
import vueJsonCompare from 'vue-json-compare'//导入组件
components: {//注册组件
vueJsonCompare
},