HarmonyOS应用开发实战:猫猫大作战-setInterception 的 willShow/willPop/didShow 三种拦截回调以及实际项目

发布时间:2026/7/28 1:25:47

HarmonyOS应用开发实战:猫猫大作战-setInterception 的 willShow/willPop/didShow 三种拦截回调以及实际项目 前言在一些业务场景中页面跳转前需要执行校验逻辑——例如用户未登录时跳转到登录页而不是目标页、权限不足时弹窗提示、需要统计跳转行为。HarmonyOS 的 Navigation 提供了setInterception路由拦截机制可以在页面跳转的各个阶段注入自定义逻辑。本文以「猫猫大作战」的登录拦截和游戏状态拦截为锚点讲解 setInterception 的 willShow/willPop/didShow 三种拦截回调以及实际项目中的应用。提示本系列不讲 ArkTS 基础语法与环境搭建假设你已跟完第 1–86 篇。本篇是阶段三第 87 篇。一、setInterception 概述1.1 接口定义interface NavigationInterception { willShow?: (context: NavigationRouteContext) void; // 页面显示前 willPop?: (context: NavigationRouteContext) void; // 页面返回前 didShow?: (context: NavigationRouteContext) void; // 页面显示后 } interface NavigationRouteContext { name: string; // 页面名称 param: Object; // 页面参数 popParam?: Object; // 返回参数 }1.2 注册拦截this.navStack.setInterception({ willShow: (context) { console.info(即将显示: ${context.name}); }, willPop: (context) { console.info(即将返回: ${context.name}); }, didShow: (context) { console.info(已显示: ${context.name}); } });二、willShow 拦截 — 页面显示前2.1 登录拦截this.navStack.setInterception({ willShow: (context) { const isLoggedIn AppStorage.getboolean(isLoggedIn) ?? false; // 未登录时跳转到登录页 if (!isLoggedIn context.name ! pages/Login) { context.param.redirectAfterLogin context.name; // 修改跳转目标为登录页 // 注意setInterception 中不支持修改 name需在业务层处理 } } });2.2 游戏状态拦截this.navStack.setInterception({ willShow: (context) { if (context.name pages/Leaderboard) { // 记录跳转来源 Analytics.report(page_view, { page: Leaderboard }); } } });三、willPop 拦截 — 页面返回前this.navStack.setInterception({ willPop: (context) { // 返回时保存页面状态 if (context.name pages/GameBoard) { AppStorage.setOrCreate(lastGameState, paused); } } });四、didShow 拦截 — 页面显示后this.navStack.setInterception({ didShow: (context) { // 页面渲染完成后的回调 console.info(页面 ${context.name} 已完全显示); } });五、常见踩坑5.1 坑一setInterception 中修改 namesetInterception 的context.name是只读的不能修改。如果需要重定向在willShow中调用replacePath// 在 pushPath 的调用方处理而非 interception 中5.2 坑二多个 stackedNavigation 共享每个 NavPathStack 实例有自己独立的拦截器如果多个 Navigation 共享同一 stack拦截器会被覆盖。六、总结setInterception 是 Navigation 提供的路由拦截机制支持 willShow/willPop/didShow 三种粒度的拦截回调。核心要点willShow页面显示前拦截适合登录校验、埋点willPop页面返回前拦截适合保存状态didShow页面显示后回调适合统计context.name 只读不支持重定向下一篇预告第 88 篇将深入 Split 分栏模式——大屏设备上的双栏布局。如果这篇文章对你有帮助欢迎点赞、收藏⭐、关注你的支持是我持续创作的动力相关资源Navigation 跳转文档Navigation 组件参考开源鸿蒙跨平台社区第 86 篇NavPathStack 查询第 88 篇Split 分栏模式

相关新闻