區別
通過注入路由器,我們可以在任何組件內通過 this.$router 訪問路由器,也可以通過 this.$route 訪問當前路由
this.$router 相當於一個全局的路由器對象,包含了很多屬性和對象(比如 history 對象),任何頁面都可以調用其 push(), replace(), go() 等方法。
this.$route 表示當前路由對象,每一個路由都會有一個 route 對象,是一個局部的對象,可以獲取對應的 name, path, params, query 等屬性。
想要導航到不同的 URL,則使用 router.push 方法。這個方法會向 history 棧添加一個新的記錄,所以,當用戶點擊瀏覽器后退按鈕時,則回到之前的 URL。
當你點擊
this.$router詳解
this.$router.push()
//url字符串
this.$router.push('/home')
//對象
this.$router.push({path:'home'})
//命名的路由
this.$router.push({name:'user', params:{userId: '123'}})
//帶查詢參數,變成 /register?plan=private
this.$router.push({path:'register', query:{plan:private}})
注意:如果提供了 path,params 會被忽略,上述例子中的 query 並不屬於這種情況。取而代之的是下面例子的做法,你需要提供路由的 name 或手寫完整的帶有參數的 path:
const userId = '123';
this.$router.push({path:`/user/${userId}`}); //->/user/123
this.$router.push({name:'user', params:{userId}}); //->/user/123
//這里的 params 不生效
this.$router.push({path:'/user', params:{userId}}); //->/user
同樣的規則也適用於 router-link 組件的 to 屬性。
總結:
params 傳參,push 里面只能是 name:'xxx',不能是 path:'/xxx',因為 params 只能用 name 來引入路由,如果這里寫成了 path ,接收參數頁面會是 undefined。
路由傳參的方式:
//手寫完整的 path:
this.$router.push({path: `/user/${userId}`});
//獲取參數:
this.$route.params.userId
//用 params 傳遞:
this.$router.push({name:'user', params:{userId: '123'}});
//獲取參數:
this.$route.params.userId
//url 形式:url 不帶參數,http:localhost:8080/#/user
//用 query 傳遞:
this.$router.push({path:'/user', query:{userId: '123'}});
//獲取參數:
this.$route.query.userId
//url 形式:url 帶參數,http:localhost:8080/#/user?userId=123
直白的說,query 相當於 get 請求,頁面跳轉的時候可以在地址欄看到請求參數,params 相當於 post 請求,參數不在地址欄中顯示。
要注意,以 / 開頭的嵌套路徑會被當作根路徑。 這讓你充分的使用嵌套組件而無須設置嵌套的路徑。
this.$router.replace()
描述:同樣是跳轉到指定的url,但是這個方法不會向history里面添加新的記錄,點擊返回,會跳轉到上上一個頁面。上一個記錄是不存在的。
this.$router.go(n)
相對於當前頁面向前或向后跳轉多少個頁面,類似 window.history.go(n)。n可為正數可為負數。正數返回上一個頁面
//前進一步,等同於history.forward()
router.go(1)
//后退一步,等同於history.back()
router.go(-1)
//前進3步
router.go(3)
//如果history記錄不夠用,就默默