interceptRouterMethod.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. // 在router 方法中加拦截
  2. import router from '@/router'
  3. import store from '@/store';
  4. // 找到要跳转到的那个路由信息
  5. const getToRoute=(path)=>{
  6. const allRoutes=router.getRoutes()
  7. let routesItem={}
  8. allRoutes.forEach(route => {
  9. if(route.path===path){
  10. routesItem=route
  11. }
  12. });
  13. return routesItem
  14. }
  15. const routerPush=router.push //保存原来的push函数
  16. // 重写push函数
  17. router.push = function push(location) {
  18. // location 可能是string 也可能是obj 完全取决于 你是怎么调push的
  19. // console.log('push');
  20. // console.log(location);
  21. let path=''
  22. let query=null
  23. // 判断location是string 还是obj
  24. if(typeof location === 'string'){
  25. path=location
  26. }else{
  27. path=location.path
  28. query=location.query
  29. }
  30. // 判断是否已经存在面包屑中
  31. let index=-1
  32. store.state.breadCrumbList.forEach((item,e) => {
  33. if(item.path === path){
  34. index=e
  35. }
  36. });
  37. if(index===-1){//不存在
  38. const routesItem=getToRoute(path)
  39. store.commit('setBreadCrumb', routesItem)
  40. }else{
  41. // console.log('拦截路由push改为返回');
  42. const _index=index-(store.state.breadCrumbList.length-1)
  43. if(_index!==0){
  44. router.go(_index)
  45. }
  46. setTimeout(() => {
  47. if(query){
  48. router.replace({
  49. query:query
  50. })
  51. }else{
  52. router.replace(path)
  53. }
  54. }, 10);
  55. return
  56. }
  57. // 调用原来的push函数,并捕获异常
  58. return routerPush.call(this, location).catch(error => error)
  59. }
  60. // 监听路由后退事件
  61. const listenRouterBack=()=>{
  62. if(window.history&&window.history.pushState){{
  63. $(window).on('popstate',()=>{
  64. console.log('路由后退');
  65. const path=window.location.pathname
  66. const routesItem=getToRoute(path)
  67. store.commit('setBreadCrumb', routesItem)
  68. })
  69. }}
  70. }
  71. listenRouterBack()