我这个业务需求是根据后台传给我的树形结构数据写的一个选择仓库的功能
由于一开始选框架选错了用cube ui 导致现在好多功能都必须自己写,所以才有了现在。
上图是我的第一级别
上图是我的最后一级
我这里实现是用的递归
首先当然是在页面写上获取仓库的接口啦
先上html
<div class="apply-material-min">
<p class="back">
<span v-show="parentId!=-1" @click="backclick">返回上一级</span>//这里是判断是否存在返回上级
</p>
<div class="material-list">
<ul>
<li v-for="(item,index) in treeList" :key="index" :id="item.id" @click="choosemater(item)">
{{item.name}}
<i class="cubeic-arrow" v-show="item.children.length!=0"></i>
</li>
</ul>
</div>
</div>
js代码
data(){
return{
parentId: -1,//判断是否存在上一级
treeList: [],//仓库列表
materialTree: [],//暂存的仓库列表
parentNames: [],//父级仓库名
}
}
//下面是方法
getWarehouse() {
chooseWarehouse().then(json => {
this.treeList=[];//这个是存放仓库名的数组
this.materialTree = json.data;//这个是暂时存放仓库名的数组
this.getChild(0, this.materialTree);//这里是调用递归方法 初始化
});
},
choosemater(item) {
// this.current = id;
if (item.type == 1 && item.children.length == 0) {//这里是判断是否还存在下一级以及是否到仓库名 仓库名的type为2 不是仓库名则为1
console.log("下面暂无仓库");
// this.parentId = -1;
return;
} else if (item.type == 2) {
// console.log(this.parentNames.toString() + "," + item.name);
this.$emit("applyMaterial", "选择物料(二级)", item.id);//我这里是需要选择仓库在跳转其他页面
return;
}
this.parentNames.push(item.name);//存放每点击的仓库名
this.treeList = [];
this.getChild(item.id, this.materialTree);
this.treeList = this.treeList;
this.parentId = item.parent_id;
return;
},
backclick() {
this.treeList = [];
this.getChild(this.parentId, this.materialTree);
this.parentNames.splice(this.parentNames.length - 1, 1);//点击返回上级时删除上次点击的仓库名
},
getChild(id, children) {//这里就是递归获取每一级的仓库 传入仓库id和树形和结构数据
let _this = this;
children.forEach(function(item) {
if (item.id == id) {//判断你点击的仓库名并拿到该仓库的上一级id
_this.parentId = item.parent_id;
}
if (item.parent_id == id) {
_this.treeList.push(item);
} else {
_this.getChild(id, item.children);
}
});
if (id == 0) {//我的第一级id为0
this.parentId = -1;//让返回上一级按钮隐藏
}
}
可能注释不是很详细,
第一次发表这么长一段 有什么问题可以在下面说一下,我看到就回复
在上次的基础上多加了一点注释,还有写了data里面的申明