vue-router中router.push、router.replace、router.go的区别

本文深入讲解Vue.js中router.push和router.replace方法的使用,包括如何通过字符串、对象和命名路由进行页面跳转,同时探讨了如何传递参数和查询字符串,以及如何利用这些方法实现历史记录的管理和前进后退功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

router.push

想要导航到不同的 URL,则使用 router.push 方法。这个方法会向 history 栈添加一个新的记录,所以,当用户点击浏览器后退按钮时,则回到之前的 URL。

<router-link :to="...">  == router.push(...)  == window.history.pushState(...)

// literal string path
router.push('home')

// object
router.push({ path: 'home' })

// named route
router.push({ name: 'user', params: { userId: 123 }})

// with query, resulting in /register?plan=private
router.push({ path: 'register', query: { plan: 'private' }})
const userId = 123
router.push({ name: 'user', params: { userId }}) // -> /user/123
router.push({ path: `/user/${userId}` }) // -> /user/123
// This will NOT work
router.push({ path: '/user', params: { userId }}) // -> /user

router.replace

跟 router.push 功能一样,唯一的不同就是,它不会向 history 添加新记录,只是替换掉当前的 history 记录。

<router-link :to="..." replace> == router.replace(...) == windows.history.replaceState(...)

router.go

这个方法的参数是一个整数,意思是在 history 记录中向前或者后退多少步,类似 window.history.go(n)

 router.go(...)  == windows.history.go

// go forward by one record, the same as history.forward()
router.go(1)

// go back by one record, the same as history.back()
router.go(-1)

// go forward by 3 records
router.go(3)

// fails silently if there aren't that many records.
router.go(-100)
router.go(100)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值