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
});
};
},
更多推荐
已为社区贡献4条内容
所有评论(0)