路径参数处理
- 定义路由时指定参数:
在定义路由时,使用动态参数语法。例如,在
express
(一个常用于后端路由,但原理类似前端路由)中,定义一个带路径参数的路由为/user/:id
,在前端路由库(如vue-router
)中也类似。在纯JavaScript实现中,可以自定义规则,如const routes = [ { path: '/user/:id', component: UserComponent } ];
- 解析路径参数:
当匹配到路由时,从路径中提取参数。以
/user/123
为例,通过正则表达式或字符串操作来提取123
。比如:
function parsePathParams(path, route) {
const pathParts = path.split('/');
const routeParts = route.path.split('/');
const params = {};
routeParts.forEach((part, index) => {
if (part.startsWith(':')) {
params[part.slice(1)] = pathParts[index];
}
});
return params;
}
查询参数处理
- 获取查询参数:
在JavaScript中,可以通过
window.location.search
获取查询字符串。例如,对于http://example.com?name=John&age=30
,window.location.search
返回?name=John&age=30
。
- 解析查询参数:
使用
URLSearchParams
对象(现代浏览器支持)来解析查询参数,如下:
function parseQueryParams() {
const searchParams = new URLSearchParams(window.location.search);
const params = {};
searchParams.forEach((value, key) => {
params[key] = value;
});
return params;
}
确保参数正确传递和解析
- 传递参数:
- 在导航到新路由时,将参数作为属性或状态传递给目标组件。例如,在
vue-router
中可以通过$router.push({ path: '/user', query: { name: 'John' } });
传递查询参数。
- 在自定义实现中,可以在路由配置对象中添加一个
params
属性,在导航时传递:const route = { path: '/user', component: UserComponent, params: { id: 123 } };
- 解析和使用参数:
在目标组件(无论是自定义组件还是路由对应的页面组件)中,通过上述解析函数获取并使用参数。例如:
const pathParams = parsePathParams(window.location.pathname, currentRoute);
const queryParams = parseQueryParams();
hash模式和history模式差异
- hash模式:
- URL形式:URL中带有
#
,如http://example.com/#/user/123
。
- 参数解析:参数解析与上述方法相同,但由于
#
后的部分不会发送到服务器,所以服务器端不会感知这部分参数,仅前端处理。
- 监听变化:通过监听
hashchange
事件来监测路由变化,例如:
window.addEventListener('hashchange', () => {
// 重新解析路径和查询参数
const path = window.location.hash.slice(1);
const pathParams = parsePathParams(path, currentRoute);
const queryParams = parseQueryParams();
// 处理路由变化逻辑
});
- history模式:
- URL形式:与正常URL一样,如
http://example.com/user/123
。
- 参数解析:同样使用上述方法解析参数,但需要注意,由于没有
#
,服务器可能会尝试解析路径,需要在服务器端配置重定向,确保所有路径都返回前端应用入口,由前端进行路由匹配。
- 监听变化:通过
history.pushState()
和history.replaceState()
方法来改变URL,通过监听popstate
事件来监测路由变化,例如:
window.addEventListener('popstate', () => {
const path = window.location.pathname;
const pathParams = parsePathParams(path, currentRoute);
const queryParams = parseQueryParams();
// 处理路由变化逻辑
});