结构如下:
分三步
1. controller中添加数据
@RequestMapping({"/", "/index"})
public String indexPage(Model model) {
List<CategoryEntity> list = categoryService.listWithTree();
List<CategoryEntity> parents = new ArrayList<>();
Map<String, List<CategoryEntity>> children = list.stream().peek(cat -> {
CategoryEntity parent = new CategoryEntity();
parent.setId(cat.getId());
parent.setName(cat.getName());
parents.add(parent);
}).collect(Collectors.toMap(k -> k.getId().toString(), v -> v.getChildren()));
model.addAttribute("parents", parents);
model.addAttribute("children", JSON.toJSONString(children));
return "index";
}
2. 页面使用input保存传来的数据
<div class="header_main_left">
<!-- 储存数据 -->
<input id="categoryList" hidden th:value="${children}">
<ul>
<li th:each="category: ${parents}">
<a href="#" class="header_main_left_a" th:attr="ctg-data=${category.id}"><b th:text="${category.name}"></b></a>
</li>
</ul>
</div>
3. js文件中通过id获取这个input的值
$(function () {
let children = JSON.parse($('#categoryList').val())
console.log(children)
//.....
}