Vue-element-admin 导出json和导入json文件的方法
作者:ogenes
这篇文章主要介绍了Vue-element-admin导出json和导入json文件,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
应用场景:
有一个菜单管理的功能,主要用来跟管理后台的菜单对应,方便后台菜单权限控制。 每次新加功能菜单都需要开发人员在后台手动输入,在测试环境操作完待发布时又要到生产环境操作一遍,非常繁琐。
为了简化操作流程,计划做一个导出再导入的功能,基于适用人群和数据特征,觉得json文件比较适合。 开发人员只需要在配置一次,发布时从测试环境导出json文件,再导入到生成即可。

安装file-saver
➜ permission git:(feature/init) npm install file-saver --save
或者直接在 package.json 中添加
"file-saver": "^2.0.5",
导出
onclick: (item) => {
this.exportMenu(item)
},
………………
exportMenu(row) {
const filename = row?.menuName || 'unknown';
const data = JSON.stringify(this.generalExportData(row));//格式化导出的数据,转成JSON字符串
const blob = new Blob([data], { type: '' });
FileSaver.saveAs(blob, filename +'.json');
},
//递归格式化,用来处理要导出的json对象
generalExportData(item) {
const menu = {
parent: item.parent,
type: item.type,
name: item.name,
title: item.title,
icon: item.icon,
path: item.path
}
if (item.children) {
menu.children = [];
item.children.forEach(child => {
menu.children.push(this.generalExportData(child))
})
}
return menu;
},
导入
<el-upload
v-permission="['MenuAdd']"
:limit="1"
action="https://jsonplaceholder.typicode.com/posts/"
ref="upload"
accept=".json"
:file-list="fileList"
:show-file-list="false"
:on-change="importMenu"
>
<el-button
v-loading="uploadLoading"
v-no-more-click
class="el-icon-upload"
type="primary"
>
{{ $trans_btn('import') }}
</el-button>
</el-upload>
importMenu(file) {
let reader = new FileReader();
reader.readAsText(file.raw);
reader.onload = (e) => {
this.uploadLoading = true;
const menu = JSON.parse(e.target.result);//转成JSON对象
//提交给后端处理
importMenu({systemId: this.systemId, menu: menu}).then((res) => {
if (res.code > 0) {
this.$message.error(res.msg)
} else {
this.$message.success(this.$trans('msg.success'));
this.saveSuccess();//处理成功要重新渲染列表
}
this.uploadLoading = false
}).catch((e) => {
console.log(e);
this.uploadLoading = false
});
};
},到此这篇关于Vue-element-admin 导出json和导入json文件的文章就介绍到这了,更多相关Vue-element-admin 导出json内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
