用于个人笔记
做的一个后台管理系统,需要进行JSON文件的导入导出。
导出
// 导出JSON
async handleExportJSON () {
const data = JSON.stringify(this.basicInfoData)
//encodeURIComponent解决中文乱码
const uri = `data:text/csv;charset=utf-8,\ufeff${encodeURIComponent(data)}`
//通过创建a标签实现
const link = document.createElement('a')
link.href = uri
// 调用版本api,生成版本信息
const newPackage = await this.newTemplate()
//对下载的文件命名
const jsonName = `${this.basicInfoData.name}-version-${newPackage.version}`
link.download = jsonName
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
}
导入JSON文件的数据
<!-- 使用饿了么input代替原始input显示 -->
<el-button type="primary" @click="handleShow" size="mini">Upload</el-button>
<!-- 原始input******利用了input框 type='file'的上传功能 -->
<form name=formen>
<input @click="handleImportJSON" name="data2" style="display:none" class="MyButtion" id="data2" type="file" value="">
</form>
//次方法是用于隐藏原始input‘太丑’的样式,用了饿了么的input来代替
private handleShow () {
(document as any).formen.data2.click()
}
// 导入JSON
async handleImportJSON () {
const _this = this
const importJSON = document.getElementById('data2') || { onchange: null }
importJSON.onchange = await function () {
const file = (this as any).files[0]
if (!!file) {
const reader = new FileReader()
reader.readAsText(file, 'gbk')//gbk编码
reader.onload = function () {
try {
_this.sendResult() //下一步动作
console.log(JSON.parse(`${this.result}`), 'this is the Json Data')
} catch (err) {
_this.$notify({
title: 'warning',
message: 'Please upload the JSON file format',
type: 'warning',
})
}
}
}
}
}
好了,基本就是这样子,可能做的还有一些考虑不完善的地方,不过具体思路就是这样,也可以满足业务需求了,下面贴两张效果图吧(打码打码--!)。