ZK不使用shadow组件实现面包屑导航的MVVM开发方法
面包屑路径导航的ZK MVVM实现方案(无组件依赖)
一、动态面包屑渲染的实现方式
- 社区版ZK从6.x开始原生支持带模型绑定的横向布局组件,完全可以替代
实现动态内容渲染,不需要手动向 <div id="placeHolder" />这类占位符中动态添加子组件。 - 核心逻辑是将面包屑容器直接绑定到ViewModel中存储路径分段的ListModel上,由框架自动根据模型数据渲染对应的链接、分隔符内容,所有渲染逻辑不需要手动操作DOM。
- 替换原zul中占位符的代码示例:
<hlayout model="@load(vm.crumbs)" spacing="4px"> <template name="model" var="crumb"> <a label="@load(crumb.displayName)" onClick="@command('navigateToPath', crumb=crumb)" sclass="@load(crumb.isCurrent ? 'current-breadcrumb' : 'link-breadcrumb')"/> <label if="@load(!crumb.isLast)" value="/" sclass="breadcrumb-separator"/> </template> </hlayout>
- 这种写法和
的渲染效果完全一致,是社区版ZK原生支持的能力,不需要引入额外的Shadow组件。
二、面包屑点击交互的MVVM实现
核心ViewModel结构
不需要获取前端组件引用,所有状态和业务逻辑都在ViewModel中完成:
- 定义两个核心模型:
ListModelList<CrumbItem> crumbs:存储面包屑的每个路径分段。每个分段是简单POJO,包含四个属性:fullPath(分段对应的完整路径)、displayName(页面显示的文本)、isCurrent(是否为当前所在路径)、isLast(是否为面包屑的最后一个分段)- 原有
ListModelList<FileMeta> files:存储当前路径下的文件列表,保持原绑定逻辑不变
- 定义导航命令方法,处理所有点击交互:
- 接收前端传入的目标路径分段参数
- 重新生成面包屑列表:截断到点击的层级,移除更深层级的分段
- 重新加载目标路径下的文件列表,更新files模型
- 模型变更会自动触发前端同步刷新,不需要手动操作组件
参考ViewModel代码
public class MyFilesViewModel { private ListModelList<FileMeta> files = new ListModelList<>(); private ListModelList<CrumbItem> crumbs = new ListModelList<>(); private final Path rootPath = Paths.get("/user/home"); private Path currentPath; @Init public void init() { navigateToPath(null); } @Command public void navigateToPath(@BindingParam("crumb") CrumbItem targetCrumb) { // 避免重复加载当前所在路径 Path targetPath = targetCrumb == null ? rootPath : targetCrumb.getFullPath(); if (targetPath.equals(currentPath)) return; currentPath = targetPath; rebuildBreadcrumbs(targetPath); loadFilesUnderPath(targetPath); } // 根据目标路径重新生成面包屑列表 private void rebuildBreadcrumbs(Path targetPath) { crumbs.clear(); Path accumulatedPath = rootPath; boolean isRootCurrent = accumulatedPath.equals(targetPath); crumbs.add(new CrumbItem(accumulatedPath, "Root", isRootCurrent, isRootCurrent)); List<String> segments = rootPath.relativize(targetPath).iterator(); for (int i = 0; i < segments.size(); i++) { accumulatedPath = accumulatedPath.resolve(segments.get(i)); boolean isCurrent = accumulatedPath.equals(targetPath); crumbs.add(new CrumbItem(accumulatedPath, segments.get(i), isCurrent, i == segments.size() -1)); } } // 加载目标路径下的文件列表 private void loadFilesUnderPath(Path targetPath) { files.clear(); try (Stream<Path> pathStream = Files.list(targetPath)) { pathStream.filter(Files::isRegularFile) .map(FileMeta::new) .forEach(files::add); } catch (IOException e) { // 目录读取异常处理 } } }
关键注意事项
- 整个实现过程中完全不需要操作占位div的组件树,所有动态渲染、状态更新都由MVVM的双向绑定机制自动完成
- 可以通过自定义CSS类调整面包屑样式:当前路径的分段去掉链接样式、分隔符设置浅灰色,不需要额外的JS逻辑
- 原参考示例中使用的
属于高版本ZK社区版内置的Shadow元素特性,低版本社区版不支持时,上述原生model绑定的实现方式是官方推荐的替代方案
内容的提问来源于stack exchange,提问作者Mohammad Irfan
相关产品推荐
相关产品推荐

