vue 阻止$router.back(1)跳转出站点

151 阅读1分钟
思路
  1. 获取上一个跳转的路由
  2. 根据上一个路由来源判断,重置即将要跳转的路由,从而达到阻止跳出站点

image.png

这里用到了路由钩子函数``` beforeRouteEnter ``通过from获取上一个路由

beforeRouteEnter(to, from, next) {
  console.log(from.path)
  next(vm => {
    console.log(from.path)
    vm.fromPath = from.path
  })
},

接下来就根据获取到的值判断就好了,注意路由钩子函数里的this是无效的,我这用了vm代替this获取

methods: {
  goback () {
    if(this.fromPath == '' || this.fromPath == '/') {
      this.$router.push('/dashboard')
    } else {
      this.$router.back(1)
    }
  },
  }

这样问题就解决了