vue-router - 如何获取上一页网址?

新手上路,请多包涵

我想在 vue-router 中获取上一页链接或网址。像这样。怎么做?

 const link = this.$router.getPrevLink(); // function is not exist?
this.$router.push(link);

近概念是 this.$router.go(-1)

 this.$router.go(-1);

原文由 narupo 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 2.3k
2 个回答

vue-router 的所有 导航守卫 都将先前的路由作为 from 参数接收。

每个守卫函数都接收三个参数:

  • to: Route :被导航到的目标路由对象。

  • from: Route :正在导航的当前路线。

  • next: Function :必须调用此函数来解决钩子。该操作取决于提供给 next 的参数

例如,您可以使用 beforeRouteEnter ,一个组件内的导航守卫,来获取先前的路线并将其存储在您的数据中..

 ...
data() {
 return {
   ...
   prevRoute: null
 }
},
beforeRouteEnter(to, from, next) {
  next(vm => {
    vm.prevRoute = from
  })
},
...

然后就可以使用 this.prevRoute.path 获取之前的URL。

原文由 Husam Ibrahim 发布,翻译遵循 CC BY-SA 4.0 许可协议

对于带有 Vue Router 4 的 Vue 3,我的解决方案是:

 this.$router.options.history.state.back

最终代码:

 export default defineComponent({
  name: 'Error404',
  data () {
    return {
      lastPath: null
    }
  },
  created () {
    this.lastPath = this.$router.options.history.state.back
  },
  computed: {
    prevRoutePatch () {
      return this.lastPath ? this.lastPath : '/dashboard'
    }
  }
})

问候。

原文由 David Becerra Montellano 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题