推荐计划开发需求:在应用所有路由中保留refCode查询字符串
保留推荐码(refCode)在所有路由跳转中的实现方案
要实现跨路由保留refCode查询参数,核心思路是在路由跳转时自动携带该参数,下面分不同场景给出具体实现:
通用前端原生方案(无框架)
通过拦截同域内的链接点击事件,自动给目标URL附加refCode参数:
// 全局监听链接点击 document.addEventListener('click', function(e) { const link = e.target.closest('a'); // 跳过新窗口打开、跨域链接 if (!link || link.target === '_blank' || link.host !== window.location.host) return; e.preventDefault(); const currentParams = new URLSearchParams(window.location.search); const refCode = currentParams.get('refCode'); if (refCode) { const targetUrl = new URL(link.href); targetUrl.searchParams.set('refCode', refCode); window.location.href = targetUrl.toString(); } else { window.location.href = link.href; } });
同时,建议在页面加载时把refCode存入本地存储,防止刷新后丢失:
// 页面加载时初始化 window.addEventListener('load', function() { const refCode = new URLSearchParams(window.location.search).get('refCode'); if (refCode) { localStorage.setItem('refCode', refCode); } });
Vue 项目方案
利用Vue Router的全局导航守卫,自动给目标路由添加refCode参数:
// router/index.js import { createRouter, createWebHistory } from 'vue-router'; const router = createRouter({ history: createWebHistory(), routes: [/* 你的路由配置 */] }); router.beforeEach((to, from, next) => { // 优先从来源路由取,没有则从本地存储取 const refCode = from.query.refCode || localStorage.getItem('refCode'); if (refCode && !to.query.refCode) { // 给目标路由追加refCode参数 to.query.refCode = refCode; // 更新本地存储 localStorage.setItem('refCode', refCode); next({ path: to.path, query: to.query }); } else { next(); } }); export default router;
React 项目方案
自定义带参数的Link组件
替换项目中所有内部跳转的Link为自定义组件,自动携带refCode:
import { Link, useLocation } from 'react-router-dom'; export const RefLink = ({ to, ...props }) => { const location = useLocation(); const refCode = new URLSearchParams(location.search).get('refCode') || localStorage.getItem('refCode'); let targetTo = to; if (refCode) { if (typeof to === 'string') { const url = new URL(to, window.location.origin); url.searchParams.set('refCode', refCode); targetTo = `${url.pathname}${url.search}`; } else { targetTo = { ...to, search: new URLSearchParams(to.search).set('refCode', refCode).toString() }; } } return <Link to={targetTo} {...props} />; };
编程式导航处理
自定义导航钩子,确保编程式跳转也携带参数:
import { useNavigate, useLocation } from 'react-router-dom'; export const useRefNavigate = () => { const navigate = useNavigate(); const location = useLocation(); return (to, options) => { const refCode = new URLSearchParams(location.search).get('refCode') || localStorage.getItem('refCode'); let targetTo = to; if (refCode) { if (typeof to === 'string') { const url = new URL(to, window.location.origin); url.searchParams.set('refCode', refCode); targetTo = `${url.pathname}${url.search}`; } else { targetTo = { ...to, search: new URLSearchParams(to.search).set('refCode', refCode).toString() }; } } navigate(targetTo, options); }; };
补充注意事项
- 首次加载时,要把URL中的
refCode存入本地存储,避免刷新后参数丢失 - 可以给
refCode设置有效期,定期清理本地存储中的过期参数 - 若涉及后端跳转(如登录后跳转),需要后端配合在跳转时携带
refCode,或把参数存入会话中供前端读取
内容的提问来源于stack exchange,提问作者teterabOb
相关产品推荐
相关产品推荐

