useHZRouter.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. // 自定义路由钩子
  2. import router from "@/router";
  3. import store from '@/store'
  4. const getToRoute=(path)=>{
  5. // 找到要跳转到的那个路由信息
  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. export default function(){
  16. // 路由跳转方法
  17. const push=({path,query})=>{
  18. // 判断是否已经存在面包屑中
  19. let index=-1
  20. store.state.breadCrumbList.forEach((item,e) => {
  21. if(item.path === path){
  22. index=e
  23. }
  24. });
  25. if(index==-1){
  26. const routesItem=getToRoute(path)
  27. store.commit('setBreadCrumb', routesItem)
  28. router.push({
  29. path:path,
  30. query:query
  31. })
  32. }else{
  33. console.log('走返回逻辑',path,query);
  34. const _index=index-(store.state.breadCrumbList.length-1)
  35. router.go(_index)
  36. setTimeout(() => {
  37. router.replace({
  38. query:query
  39. })
  40. }, 10);
  41. }
  42. }
  43. const replace=({path,query})=>{
  44. if(path){
  45. router.replace({
  46. path:path,
  47. query:query
  48. })
  49. }else{
  50. router.replace({
  51. query:query
  52. })
  53. }
  54. }
  55. const go=(num)=>{
  56. // let index=num+(store.state.breadCrumbList.length-1)
  57. // const path=store.state.breadCrumbList[index].path
  58. // const routesItem=getToRoute(path)
  59. // store.commit('setBreadCrumb', routesItem)
  60. router.go(num)
  61. }
  62. return {push,replace,go}
  63. }
  64. export const listenRouterBack=()=>{
  65. if(window.history&&window.history.pushState){{
  66. $(window).on('popstate',()=>{
  67. console.log('路由后退');
  68. // const path=window.location.pathname
  69. // const routesItem=getToRoute(path)
  70. // store.commit('setBreadCrumb', routesItem)
  71. })
  72. $(window).on('pushstate',()=>{
  73. console.log('路由改变');
  74. })
  75. }}
  76. }