【前端】路由请求中参数的读取方法

0 说明

在浏览器打开链接的时候,需要读取https://www.test.com/#/?queryScene=A&queryData=B这样的路由请求中的参数,然后根据参数走不同的流程或者请求不同的接口


1 实现

方法1 vue-router

vue-router中,使用路由守卫async beforeEnter(to, from, next)
然后通过to.query.queryScene即可获得它的值A

方法2 window.location.search

封装一个方法getParameter

export function getParameter(param){
    
    
  let url = window.location.search;
  var query = url.slice(url.indexOf('?'));
  var iLen = param.length + 1;
  var iStart == query.indexOf(param + '=');
  if (iStart == -1) return '';
  iStart += iLen;
  var iEnd =query.indexOf('&', iStart);
  if (iEnd == -1) return query.substring(iStart);
  return query.subString(iStart, iEnd);
}

这样,只需要通过调用getParameter('queryData')即可获得它的值B
但是要注意,hash模式下,#符之后的内容都会被当做hash值,无法通过window.locaion.search的方式获得

方法3 window.locaion.href

因为hash模式下,存在方法2中的局限,所以将方法中的window.location.search修改为window.locaion.href即可


2 总结

获取路由请求中的参数是常见的场景,可以通过方法封装,简化代码

猜你喜欢

转载自blog.csdn.net/RogerQianpeng/article/details/128220660
今日推荐