vue-router的Hash模式search/参数部分和hash部分谁在前谁在后

1,537 阅读1分钟

this.$route.query拿到的是hash后面的search部分

image.png 如上图所示, hash的前面有?b=2,hash的后面有?a=1 , 输出的route.query{a: 1}

window.location.search拿到的是hash前面的search部分

image.png

如上图所示, hash的前面有?b=2,hash的后面有?a=1 , 输出的window.location.search?b=2

vue-router处理query的源码

image.png

  1. 调用createWebHashHistory,参数base为undefined
  2. 判断location.host,此时location.host为www.ysg.com:8088,base为undefined,所以base=location.pathname + location.search = '/' + '?b=2' = '/?b=2',接着判断base是否包含#,不包含则在base后面加上#,故最后base为/?b=2#
  3. 调用createWebHistory方法。

image.png 4. createWebHistory方法中调用useHistoryStateNavigation方法。

image.png 5. useHistoryStateNavigation方法中调用createCurrentLocation方法,该方法用于返回location/vue/router/hash/search?a=1createCurrentLocation方法内容如下:

image.png window.location详情如下:

image.png

image.png 6. 传入parseURL方法的location是字符串/vue/router/hash/search?a=1; 7. 判断location中字符#的位置,hashPos为-1; 8. 判断location中字符?的位置,searchPos为23; 9. 从location中拿到?后面的部分,这就是最后得到query的部分。

故this.$route.query 是从window.location.hash字符串?后面部分得到的。

最终结论

若是使用vue-router,应该是要将search部分放在hash部分的后面。但这种顺序与URL正常的顺序不一致,不知道会不会有其他的隐患。