跳转传参的使用
一、URL 查询参数(Query Parameters)
适用场景
-
传递少量非敏感数据(如ID、页码、搜索关键词)
-
需支持链接直接分享(参数可见)
实现方法
-
发送参数(跳转时)
// 方式1:手动拼接URL(原生JS) const itemId = 123; window.location.href = `/detail.html?id=${itemId}`;// 方式2:使用URLSearchParams(更规范) const params = new URLSearchParams(); params.set("id", 123); params.set("from", "home"); window.location.href = `/detail.html?${params.toString()}`;
-
接收参数(目标页面)
// 解析URL中的查询参数 const urlParams = new URLSearchParams(window.location.search); const id = urlParams.get("id"); // "123" const from = urlParams.get("from"); // "home"
注意事项
-
数据长度限制:URL总长度不宜超过2048字符(不同浏览器差异)。
-
编码敏感字符:使用
encodeURIComponent
处理特殊字符(如空格、&
):const keyword = "apple & orange"; const safeKeyword = encodeURIComponent(keyword); // "apple%20%26%20orange"
二、路由参数(Path Parameters)
适用场景
-
RESTful风格路径(如
/product/123
) -
参数为必要标识(如ID)
实现方法(以React Router为例)
-
定义动态路由
// 路由配置 <Route path="/product/:id" element={<ProductDetail />} />
-
跳转时传递参数
// 使用Link组件 <Link to={`/product/${item.id}`}>查看详情</Link>// 编程式导航 navigate(`/product/${item.id}`);
-
接收参数
import { useParams } from "react-router-dom";function ProductDetail() {const { id } = useParams(); // 获取路径参数return <div>Product ID: {id}</div>; }
三、状态传递(State)
适用场景
-
传递复杂对象(如JSON数据)
-
隐藏敏感参数(不在URL中暴露)
实现方法(以React Router为例)
-
跳转时携带状态
// 通过Link的state属性 <Link to="/detail" state={{ itemId: 123,userRole: "admin"}} >详情 </Link>// 编程式导航 navigate("/detail", { state: { itemId: 123 } });
-
接收状态
import { useLocation } from "react-router-dom";function DetailPage() {const location = useLocation();const { itemId, userRole } = location.state || {};// 使用数据... }
注意事项
-
页面刷新丢失:浏览器刷新后
state
会清空,需结合本地存储或URL参数持久化关键数据。 -
浏览器兼容性:现代浏览器支持,但需处理回退情况(如用户手动输入URL)。
四、本地存储(LocalStorage/SessionStorage)
适用场景
-
跨页面传递较大数据(如表单草稿)
-
需持久化参数(即使关闭浏览器)
实现方法
-
存储数据
const formData = { username: "Alice", progress: 50 }; localStorage.setItem("tempForm", JSON.stringify(formData));
-
跳转后读取
const savedData = JSON.parse(localStorage.getItem("tempForm")); if (savedData) {console.log(savedData.username); // "Alice"localStorage.removeItem("tempForm"); // 使用后清理 }
注意事项
-
隐私模式限制:无痕浏览模式下可能无法使用localStorage。
-
数据安全:避免存储敏感信息(如密码、令牌)。
五、框架特定方案(如Vue的Vuex/Pinia)
适用场景
-
全局状态共享(如用户登录信息)
-
复杂应用的多组件参数传递
实现示例(Vue3 + Pinia)
-
定义Store
// stores/params.js import { defineStore } from 'pinia';export const useParamStore = defineStore('params', {state: () => ({transferData: null}),actions: {setTransferData(data) {this.transferData = data;}} });
-
跳转前存储数据
import { useParamStore } from '@/stores/params'; const store = useParamStore();// 在组件中设置数据 store.setTransferData({ id: 456, type: "VIP" });// 执行路由跳转 router.push('/target-page');
-
目标页面读取
import { useParamStore } from '@/stores/params'; const store = useParamStore();// 获取数据 console.log(store.transferData); // { id:456, type:"VIP" }
六、对比与选型建议
方式 | 优点 | 缺点 | 适用场景 |
---|---|---|---|
URL查询参数 | 简单直观、支持分享 | 暴露数据、长度受限 | 非敏感简单参数 |
路由参数 | 语义清晰、SEO友好 | 仅适合必要标识 | RESTful资源定位 |
状态传递(State) | 隐藏参数、支持复杂对象 | 刷新后丢失 | 临时数据传递 |
本地存储 | 数据持久化、跨页面 | 需手动清理、隐私模式受限 | 表单草稿、多步骤操作 |
全局状态管理 | 集中管理、响应式更新 | 需框架支持、复杂度高 | 中大型应用状态共享 |
七、安全与最佳实践
-
敏感数据加密
-
避免在URL中传递密码、Token等,改用POST请求或加密后传递。
-
示例:使用
AES
加密ID后再拼接URL:import CryptoJS from 'crypto-js'; const encryptedId = CryptoJS.AES.encrypt('123', 'secret-key').toString();
-
-
参数校验
-
接收端需验证参数合法性(如是否为数字、是否在允许范围内)。
const id = parseInt(urlParams.get("id")); if (isNaN(id)) {throw new Error("Invalid ID parameter"); }
-
-
防XSS攻击
-
对用户输入的参数进行转义,防止注入恶意脚本:
const userInput = "<script>alert('xss')</script>"; const safeInput = userInput.replace(/</g, "<").replace(/>/g, ">");
-
通过合理选择传参方式,既能提升用户体验,又能保障应用安全性和可维护性。