溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

vue中router.push()有什么用

發(fā)布時間:2021-08-19 10:16:27 來源:億速云 閱讀:145 作者:小新 欄目:web開發(fā)

這篇文章給大家分享的是有關(guān)vue中router.push()有什么用的內(nèi)容。小編覺得挺實用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。

除了使用 <router-link> 創(chuàng)建 a 標簽來定義導航鏈接,我們還可以借助 router 的實例方法,通過編寫代碼來實現(xiàn)。

router.push(location)

想要導航到不同的 URL,則使用 router.push 方法。這個方法會向 history 棧添加一個新的記錄,所以,當用戶點擊瀏覽器后退按鈕時,則回到之前的 URL。

當你點擊 <router-link> 時,這個方法會在內(nèi)部調(diào)用,所以說,點擊 <router-link :to="..."> 等同于調(diào)用 router.push(...)。

聲明式:<router-link :to="...">

編程式:router.push(...)

該方法的參數(shù)可以是一個字符串路徑,或者一個描述地址的對象。

// 字符串
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è)計查詢參數(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

默認值: false

設(shè)置 replace 屬性的話,當點擊時,會調(diào)用 router.replace() 而不是 router.push(),于是導航后不會留下 history 記錄。即使點擊返回按鈕也不會回到這個頁面。

//加上replace: true后,它不會向 history 添加新記錄,而是跟它的方法名一樣 —— 替換掉當前的 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});

感謝各位的閱讀!關(guān)于“vue中router.push()有什么用”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,讓大家可以學到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI