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.get<boolean>('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 中修改 name
setInterception 的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 分栏模式
