this.$route.query拿到的是hash后面的search部分
如上图所示, hash的前面有
?b=2,hash的后面有?a=1 , 输出的route.query是{a: 1}。
window.location.search拿到的是hash前面的search部分
如上图所示, hash的前面有?b=2,hash的后面有?a=1 , 输出的window.location.search是?b=2。
vue-router处理query的源码
- 调用
createWebHashHistory,参数base为undefined - 判断location.host,此时location.host为
www.ysg.com:8088,base为undefined,所以base=location.pathname + location.search = '/' + '?b=2' = '/?b=2',接着判断base是否包含#,不包含则在base后面加上#,故最后base为/?b=2#; - 调用
createWebHistory方法。
4.
createWebHistory方法中调用useHistoryStateNavigation方法。
5.
useHistoryStateNavigation方法中调用createCurrentLocation方法,该方法用于返回location为/vue/router/hash/search?a=1。createCurrentLocation方法内容如下:
window.location详情如下:
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正常的顺序不一致,不知道会不会有其他的隐患。