vue-router中router.push、router.replace、router.go的區別
阿新 • • 發佈:2018-11-19
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)