ZTree 是前端常用的樹形組件,配合 Checkbox 實現權限授權界面。本文記錄新增角色授權與編輯角色權限回顯的完整落地代碼,涵蓋前端交互、後端數據組裝、權限勾選邏輯。
<ul id="functionTree" class="ztree"></ul>
var setting = {
data: {
key: { title: "t" },
simpleData: { enable: true }
},
check: { enable: true } // 啟用 Checkbox
};
$.ajax({
url: '${pageContext.request.contextPath}/rest/sys/getAllFunction',
type: 'get',
dataType: 'json',
success: function(data) {
$.fn.zTree.init($("#functionTree"), setting, data);
},
error: function() { alert('樹加載異常!'); }
});
var treeObj = $.fn.zTree.getZTreeObj("functionTree");
var nodes = treeObj.getCheckedNodes(true);
var ids = nodes.map(n => n.id).join(",");
$("input[name=funcitonIds]").val(ids);
@Transactional(readOnly = true)
public List<Map<String, Object>> queryFunByRoleId(String roleId) {
List<AuthFunction> allFuncs = queryAllAuthFunction(); // 所有權限
List<AuthFunction> roleFuncs = findFunctionByRoleId(roleId); // 角色擁有權限
List<Map<String, Object>> zNodes = new ArrayList<>();
for (AuthFunction fun : allFuncs) {
Map<String, Object> node = new HashMap<>();
node.put("id", fun.getId());
node.put("pId", fun.getpId()); // ZTree 需 pId 字段
node.put("name", fun.getName());
node.put("isParent", fun.getIsParent());
// 核心:判斷當前權限是否屬於角色,設置 checked
node.put("checked", ListIsContainsObj(roleFuncs, fun));
zNodes.add(node);
}
return zNodes;
}
private boolean ListIsContainsObj(List<AuthFunction> list, AuthFunction target) {
if (target == null || list == null || list.isEmpty()) return false;
return list.stream().anyMatch(f -> f.getId().equals(target.getId()));
}
$(document).ready(function() {
var roleId = $("#roleId").val();
loadPower(roleId); // 同步請求獲取帶 checked 標記的樹數據
$.fn.zTree.init($("#functionTree"), setting, zNodes);
});
function loadPower(roleId) {
$.ajax({
type: "post",
url: "${pageContext.request.contextPath}/rest/sys/queryFunByRoleId",
data: { "roleId": roleId },
async: false, // 必須同步,確保 zNodes 就緒再 init
dataType: "json",
success: function(data) { zNodes = data; }
});
}
public String getpId() { // ZTree 要求父節點字段名為 pId
return this.pid == null ? "0" : this.pid;
}
simpleData: { enable: true } 只需 id/pId/name 即可構建樹checked: true/false,前端無需二次遍歷async: false 確保樹數據就緒再初始化此方案經項目驗證,穩定支撐 RBAC 權限管理的樹形交互需求。