原文网址:Vue--Router--this.$router.replace()、push()、go()的区别_IT利刃出鞘的博客-CSDN博客
简介
说明
本文介绍Vue中的编程式路由的几种写法的区别,包括:this.$router.replace、his.$router.push()、his.$router.go()。
官网网址
this.$router.push()
除了使用 <router-link> 创建 a 标签来定义导航链接,我们还可以借助 router 的实例方法,通过编写代码来实现。
详见:Vue--Router--router-link与this.$router.push--使用/区别_IT利刃出鞘的博客-CSDN博客
this.$router.replace()
说明
它的作用类似于 router.push,唯一不同的是,它在导航时不会向 history 栈添加新记录,而是替换(覆盖)掉当前路由。
比如:A=> B=> C,在B=> C时用了replace,则B被C替换,历史记录的栈就成了这样:A=> C。此时,在C页面点击返回时会跳到A页面。
声明式写法
<router-link :to="..." replace>
编程式写法
this.$router.replace()
也可以直接在传递给 router.push 的 routeLocation 中增加一个属性 replace: true :
this.$route.push({ path: '/home', replace: true })
// 相当于
this.$route.replace({ path: '/home' })
实例
下单时用push方法导致路由陷入了死循环:商品详情=> push=> 下单页=> push=> 支付页=> push=> 订单列表页。订单列表页按返回会返回到支付页,再按支付页的返回键(返回写的push路由到订单列表页),这样整个流程就陷入了死循环,这绝对是不允许的。
解决方案是:路商品页=> push=> 下单页=> replace=> 支付页=> replace=> 订单列表页。这样就不会陷入死循环了,也不会在支付订单后可以再退回到支付页和下单页了。
this.$router.go(n)
说明
该方法采用一个整数作为参数,表示在历史堆栈中前进或后退多少步,类似于 window.history.go(n)。
括号内直接填写数字n。正数:前进n个页面,负数:后退n个页面
示例
// 向前移动一条记录,与 router.forward() 相同
router.go(1)
// 返回一条记录,与 router.back() 相同
router.go(-1)
// 前进 3 条记录
router.go(3)
// 如果没有那么多记录,静默失败
router.go(-100)
router.go(100)