ZIP的数据从接口传递数据流过来。解析数据流,并将zip的目录绑定到tree中。
1.引入插件jszip:
yarn add jszip
2.在需要引用的页面引用:
import JSZip from 'jszip'
3. 实现代码
api(option).then((res)=>{ // 接口获取zip的数据流
let jszip = new JSZip()
jszip.loadAsync(res.data).then(zip=>{
let myData=[]
that.transformData(zip, myData,0,)
that.treeData=myData // 将数据绑定到tree
that.$nextTick(()=>{
that.expandedKeys=['0']
})
})
});
transformData(obj, myData, level = 0,) {
let id=0
if(Object.keys(obj.files).length==0){
let fname=this.fileName.substring(0, this.fileName.lastIndexOf("."))
let rootData={id:'0',parentId:'', key:'0',title:fname, children:[]}
myData.push(rootData)
}else{
for (let key in obj.files) {
let array=key.split('/').filter(item => item != '')
if(array.length == level+1){
if (obj.files[key].dir) {
if(level==0){
let rootData={parentId:'', key:'0',title:array[level], children:[]}
myData.push(rootData)
this.transformData(obj, rootData,level+1)
}else{
if(key.indexOf(myData.fullName)===0 && key!= myData.fullName){
let newData={ key:myData.id+'-'+id,parentId:myData.id, title:array[level],children:[],fullName:key}
myData.children.push(newData)
id++
this.transformData(obj, newData,level+1)
}
}
}else{ // 文件
if(key.indexOf(myData.fullName)==0 && key!=myData.fullName){
let data= {parentId:myData.id, key:myData.id+'-'+id,title:array[level],}
myData.children.push(data)
id++
}
}
}
}
}
return myData;
},