如何在Spartacus PDP页面添加CanDeactivate类型路由守卫
无显式PDP路由配置下的跳转拦截解决方案
你不需要为PDP页单独配置路由项就能实现拦截,以下是3种可直接落地的方案:
方案1:全局路由守卫路径匹配
无需给PDP路由单独配置关联组件,在全局守卫中按路径规则匹配拦截即可,适配所有前端路由框架场景:
- Vue Router示例:
router.beforeEach((to, from, next) => { // 按你的PDP路径规则调整匹配逻辑,比如所有路径以 /product/ 开头的都是PDP页 const isPdpPage = to.path.match(/^\/product\/\d+/) const formNotCompleted = localStorage.getItem('current_form_status') !== 'finished' if (isPdpPage && formNotCompleted) { // 阻止跳转,可按需加提示、跳转至表单页 next(false) return } next() })
- React Router示例(v6+):
const router = createBrowserRouter([ // 原有路由配置不变,不需要新增PDP相关配置 ]) router.subscribe((state) => { const isPdpPage = state.location.pathname.match(/^\/product\/\d+/) const formNotCompleted = localStorage.getItem('current_form_status') !== 'finished' if (isPdpPage && formNotCompleted) { alert('请先完成表单填写') window.history.back() } })
方案2:原生导航事件拦截(适配无路由框架/完全动态路由场景)
如果项目没有用前端路由框架、或者PDP路由是完全动态渲染无固定配置的,直接监听浏览器全局事件实现拦截:
// 监听前进、后退、路由切换操作 window.addEventListener('popstate', () => { const isPdpPage = location.pathname.match(/^\/product\/\d+/) const formNotCompleted = localStorage.getItem('current_form_status') !== 'finished' if (isPdpPage && formNotCompleted) { history.go(1) alert('请先完成表单填写') } }) // 拦截页面刷新、关闭、外链跳转操作 window.addEventListener('beforeunload', (e) => { const formNotCompleted = localStorage.getItem('current_form_status') !== 'finished' if (formNotCompleted) { e.preventDefault() e.returnValue = '表单尚未完成,确定要离开当前页吗?' } })
方案3:跳转入口前置校验(零路由修改成本)
如果PDP页的跳转入口是可枚举的(比如商品卡片、搜索结果、推荐位点击),直接在跳转触发逻辑前加校验即可,不需要修改任何路由相关配置:
// 原有PDP跳转逻辑 const handleJumpToPdp = (productId) => { const formNotCompleted = localStorage.getItem('current_form_status') !== 'finished' if (formNotCompleted) { alert('请先完成表单填写') return } // 原跳转逻辑不变 location.href = `/product/${productId}` }
内容的提问来源于stack exchange,提问作者Indrajeet Gajbhiye
相关产品推荐
相关产品推荐

