1.问题描述
404页面本身来源复杂,通过this.$router.go(-1)this.$router.go(-2)或者history.back()都很难覆盖所有场景,
而且上面的方案很容易导致死循环-上一个页面出错跳到404,返回回去又继续跳到404。

2.问题根源
此时问题关键点,上一个路由到底是什么,此时就需要用到组件内的路由守卫

3.知识点
beforeRouteEnter中无法通过this获取到组件实例,但是可以在回调函数next中访问组件实例

4.相关代码
页面返回上一级按钮绑定back事件

data () {
  return {
    fromPathName: ''
  }
},
beforeRouteEnter: (to, from, next) => {
  next(vm => {
    vm.fromPathName = from.name
  })
},
methods: {
  back: function () {
    if (this.fromPathName === 'details' || this.fromPathName === 'video') {
      this.$router.push({name: 'library'})
    } else {
      this.$router.push({name: this.fromPathName})
    }
  }
}

相关文章:https://www.jianshu.com/p/691379025334

作者 铁血 汉子 2019年3月13日
2024/04/20/06:14:04am 2019/3/13/6:08:54
0 1593