router.push(location)
http://www.itdecent.cn/p/ee7ff3d1d93d
除了使用 <router-link> 創(chuàng)建 a 標(biāo)簽來定義導(dǎo)航鏈接,我們還可以借助 router 的實(shí)例方法,通過編寫代碼來實(shí)現(xiàn)。
router.push(location)
想要導(dǎo)航到不同的 URL,則使用 router.push 方法。這個(gè)方法會向 history 棧添加一個(gè)新的記錄,所以,當(dāng)用戶點(diǎn)擊瀏覽器后退按鈕時(shí),則回到之前的 URL。
當(dāng)你點(diǎn)擊 <router-link> 時(shí),這個(gè)方法會在內(nèi)部調(diào)用,所以說,點(diǎn)擊 <router-link :to="..."> 等同于調(diào)用 router.push(...)。
聲明式:<router-link :to="...">
編程式:router.push(...)
該方法的參數(shù)可以是一個(gè)字符串路徑,或者一個(gè)描述地址的對象。
// 字符串
router.push('home')
// 對象
this.$router.push({path: '/login?url=' + this.$route.path});
// 命名的路由
router.push({ name: 'user', params: { userId: 123 }})
// 帶查詢參數(shù),變成/backend/order?selected=2
this.$router.push({path: '/backend/order', query: {selected: "2"}});
// 設(shè)置查詢參數(shù)
this.$http.post('v1/user/select-stage', {stage: stage})
.then(({data: {code, content}}) => {
if (code === 0) {
// 對象
this.$router.push({path: '/home'});
}else if(code === 10){
// 帶查詢參數(shù),變成/login?stage=stage
this.$router.push({path: '/login', query:{stage: stage}});
}
});
// 設(shè)計(jì)查詢參數(shù)對象
let queryData = {};
if (this.$route.query.stage) {
queryData.stage = this.$route.query.stage;
}
if (this.$route.query.url) {
queryData.url = this.$route.query.url;
}
this.$router.push({path: '/my/profile', query: queryData});
replace
類型: boolean
默認(rèn)值: false
設(shè)置 replace 屬性的話,當(dāng)點(diǎn)擊時(shí),會調(diào)用 router.replace() 而不是 router.push(),于是導(dǎo)航后不會留下 history 記錄。即使點(diǎn)擊返回按鈕也不會回到這個(gè)頁面。
//加上replace: true后,它不會向 history 添加新記錄,而是跟它的方法名一樣 —— 替換掉當(dāng)前的 history 記錄。
this.$router.push({path: '/home', replace: true})
//如果是聲明式就是像下面這樣寫:
<router-link :to="..." replace></router-link>
// 編程式:
router.replace(...)
綜合案例
this.$router.push({path: '/coach/' + this.$route.params.id, query: queryData});