如何仅在/product/{slug}路由为body添加指定类并在其他路由移除
路由匹配动态修改body类名实现方案
以下是不同技术场景下的通用实现方法:
原生JavaScript(无前端框架场景)
- 监听路由变化事件,路由更新时触发类名更新逻辑
- 代码实现:
// 类名更新逻辑 function updateBodyPaddingClass() { const currentPath = window.location.pathname; // 匹配 /product/{slug} 格式路由,slug不包含斜杠的场景可直接用该正则 const isProductDetail = /^\/product\/[^/]+\/?$/.test(currentPath); const bodyEl = document.body; if (isProductDetail) { bodyEl.classList.add('product-page-bottom-padding'); } else { bodyEl.classList.remove('product-page-bottom-padding'); } } // 页面首次加载执行 window.addEventListener('load', updateBodyPaddingClass); // 监听浏览器前进后退操作 window.addEventListener('popstate', updateBodyPaddingClass); // 自定义前端路由跳转(如pushState/replaceState触发的跳转),每次跳转后手动调用updateBodyPaddingClass即可
Vue + Vue Router 场景
直接在全局路由后置守卫中处理即可:
// router/index.js 文件中添加如下代码 router.afterEach((to) => { // 方式1:匹配路由定义的规则 const isProductDetail = to.matched.some(item => item.path === '/product/:slug'); // 方式2:直接匹配路径,和原生逻辑一致 // const isProductDetail = /^\/product\/[^/]+\/?$/.test(to.fullPath); const bodyEl = document.body; if (isProductDetail) { bodyEl.classList.add('product-page-bottom-padding'); } else { bodyEl.classList.remove('product-page-bottom-padding'); } })
React + React Router v6 场景
在全局根组件中配合useLocation钩子实现:
import { useEffect } from 'react'; import { useLocation } from 'react-router-dom'; export default function App() { const { pathname } = useLocation(); useEffect(() => { const isProductDetail = /^\/product\/[^/]+\/?$/.test(pathname); const bodyEl = document.body; if (isProductDetail) { bodyEl.classList.add('product-page-bottom-padding'); } else { bodyEl.classList.remove('product-page-bottom-padding'); } // 组件卸载兜底移除类 return () => bodyEl.classList.remove('product-page-bottom-padding'); }, [pathname]) // 其他根组件逻辑 }
注意:如果你的slug字段允许包含斜杠,可以根据实际路由规则调整正则匹配逻辑,避免匹配错误。
内容的提问来源于stack exchange,提问作者S.M_Emamian
相关产品推荐
相关产品推荐

