当开发中在实现有树结构的需要时,置信大家都晓得如果一次性的把树的所有数据都申请回来再进行渲染是不太好的,因为用户兴许只须要某一节点的数据,其余的数据他不须要,获取所有数据就会造成申请慢、和渲染慢的问题,那就须要实现树懒加载性能进行优化。
这篇文章介绍如何应用 ztree 进行树的懒加载:
先通过后端获取到树结构的数据,而后利用数据初始化一个树(当然是只有一层的),data 是申请拿回来的数据,配置懒加载时申请的接口和参数
var setting = {
async: {
// 启用异步加载节点
enable: true,
url: "tree/list",
autoParam: ["id"], // 主动带上点击节点的 id
headers: {ticket: sessionStorage.getItem("ticket") },
contentType: "application/json; charset=UTF-8",
dataFilter: function () {}, // 避免 undefined 节点 bug
},
data: {
simpleData: {enable: true,},
},
view: {expandSpeed: 200,},
callback: {
beforeExpand: beforeExpand,
onAsyncSuccess: onAsyncSuccess,
onAsyncError: onAsyncError,
},
};
var zTree = $.fn.zTree.init($("#tree"), setting, data);
而后增加对应的回调函数:当懒加载申请实现后去动静增加上级节点 zTree.addNodes
var zTree = $.fn.zTree.init($("#tree"), setting, res.data);
var setting = {
async: {
// 启用异步加载节点
enable: true,
url: "tree/list",
autoParam: ["id"], // 主动带上点击节点的 id
headers: {ticket: sessionStorage.getItem("ticket") },
contentType: "application/json; charset=UTF-8",
dataFilter: function () {}, // 避免 undefined 节点 bug
},
data: {
simpleData: {enable: true,},
},
view: {expandSpeed: 200,},
callback: {
beforeExpand: beforeExpand,
onAsyncSuccess: onAsyncSuccess,
onAsyncError: onAsyncError,
},
};
function beforeExpand(treeId, treeNode) {if (!treeNode.isAjaxing) {
// 在加载中
treeNode.icon = "./zTree_v3/css/zTreeStyle/img/loading.gif";
zTree.reAsyncChildNodes(treeNode, "refresh", true);
treeNode.icon = "";
return true;
} else {layer.msg("正在加载数据中,请稍后开展节点");
return false;
}
}
function onAsyncSuccess(event, treeId, treeNode, res) {ajaxGetNodes(parseTree(JSON.parse(res).data), treeNode);
}
function onAsyncError(
event,
treeId,
treeNode,
XMLHttpRequest,
textStatus,
errorThrown
) {layer.msg("异步获取数据出现异常");
treeNode.icon = "";
zTree.updateNode(treeNode);
}
function ajaxGetNodes(treeNodeArr, currtNode) {zTree.addNodes(currtNode, 0, treeNodeArr, false);
}
// 过滤节点列表
function parseTree(data) {data.forEach(function (val) {if (val.isLeaf != 1) {
val.isParent = true;
val.open = true;
} else {
val.isParent = false;
val.open = false;
}
});
return data;
}