js-Vue Router 中的方法,父A-子B-子C依次返回,无法返回到A,BC中形成循环跳转解决

1.常用的方法

        在 Vue Router 中,有一些常用的方法用于实现路由导航和管理。以下是一些常见的 Vue Router 方法及其作用:

  1. pushrouter.push(location, onComplete, onAbort)

    • 作用:向路由历史记录中添加一个新条目,并导航到指定的路由。
    • 示例:this.$router.push('/new-route')
  2. replacerouter.replace(location, onComplete, onAbort)

    • 作用:替换当前路由为指定的路由,不会在历史记录中留下新条目。
    • 示例:this.$router.replace('/new-route')
  3. gorouter.go(n)

    • 作用:前进或后退指定步数的历史记录条目。
    • 示例:this.$router.go(-1) // 后退一页
  4. backrouter.back()

    • 作用:后退一页,相当于 go(-1)
    • 示例:this.$router.back()
  5. forwardrouter.forward()

    • 作用:前进一页,相当于 go(1)
    • 示例:this.$router.forward()
  6. resolverouter.resolve(location, current, append)

    • 作用:解析给定的位置(location)到一个完整的地址对象。
    • 示例:this.$router.resolve('/about')

这些方法可以通过 this.$router 对象来访问,通常在 Vue 组件中使用。它们提供了对路由器的操作和导航功能,可以帮助您实现页面间的切换、历史记录管理等功能。

2.问题描述

        父A-子B-子C依次返回,无法返回到A,BC中形成循环跳转。

BC中形成死循环,由于跳转记录了来时的路径一旦由a->b :返回记录路径为toA ,b->c:返回路径为toB,从c返回到b后 返回路径为toC。形成B与C死循环。

所以关键为:在B中时记录唯一由其他页面跳转到B的路径在存入返回路径时进行判断排除从C返回到B路径。在C返回到B时使用  this.$router.replace({path}),replace替换当前路由为指定的路由,不会在历史记录中留下新条目。

(1)A跳转到B

 toB(row) {let path = 'home/B'this.$router.push({path,})},

  (2)   B返回A

 BackA() {let path = this.fromPath;this.$router.replace({path})},
beforeRouteEnter(to, from, next) {next(vm => {// 表示非C返回if (to?.query?.proInfo && 0 < from.fullPath.length&&from.path==from.fullPath) {// 传入参数'proInfo'表示项目入口进入vm.fromPath = from.fullPath// setItem()方法存储 存储sessionStorage.setItem("viewProjectFromPathSession", from.fullPath);}else if(from.path){}else{// sessionStorage.getItem 读取 vm.fromPath = sessionStorage.getItem("viewProjectFromPathSession");}})},
 init(){if (this.processFromPath) {this.fromPath = this.processFromPath;}

activated() {this.init()},

在B中路由守卫,缓存记录路由跳转路径

  (3)  B跳转到C

        进行携带参数标识index

      toC(row) {let path = 'home/C'this.$router.push({path,query: { proInfo: row,index:2},})},

 (4)C返回B

 // C-BBackB() {let path = this.fromPath;this.$router.replace({path})},
	  beforeRouteEnter(to, from, next) {next(vm => {if (to?.query?.proInfo && 0 < from.fullPath.length) {// 传入参数'proInfo'表示项目入口进入vm.fromPath = from.fullPathsessionStorage.setItem("viewProjectFromPathSession", from.fullPath);}else{vm.fromPath = sessionStorage.getItem("viewProjectFromPathSession");}})},
 init(){if (this.processFromPath) {this.fromPath = this.processFromPath;}
activated() {this.init()},

在C中路由守卫,缓存记录路由跳转路径