Vue中this.$router和this.$route的區(qū)別及push()方法
官房文檔里是這樣說明的:
通過注入路由器,我們可以在任何組件內(nèi)通過 this.$router 訪問路由器,也可以通過 this.$route 訪問當(dāng)前路由
可以理解為:
this.$router 相當(dāng)于一個全局的路由器對象,包含了很多屬性和對象(比如 history 對象),任何頁面都可以調(diào)用其 push(), replace(), go() 等方法。
this.$route 表示當(dāng)前路由對象,每一個路由都會有一個 route 對象,是一個局部的對象,可以獲取對應(yīng)的 name, path, params, query 等屬性。
關(guān)于 push() 方法:
想要導(dǎo)航到不同的 URL,則使用 router.push 方法。這個方法會向 history 棧添加一個新的記錄,所以,當(dāng)用戶點(diǎn)擊瀏覽器后退按鈕時(shí),則回到之前的 URL。
當(dāng)你點(diǎn)擊 <router-link> 時(shí),這個方法會在內(nèi)部調(diào)用,所以說,點(diǎn)擊 <router-link :to='...'> 等同于調(diào)用 router.push(...)。
push() 方法的調(diào)用:
//字符串 this.$router.push(’home’) //對象 this.$router.push({path:’home’}) //命名的路由 this.$router.push({name:’user’, params:{userId: ’123’}}) //帶查詢參數(shù),變成 /register?plan=private this.$router.push({path:’register’, query:{plan:private}})
注意:如果提供了 path,params 會被忽略,上述例子中的 query 并不屬于這種情況。取而代之的是下面例子的做法,你需要提供路由的 name 或手寫完整的帶有參數(shù)的 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
同樣的規(guī)則也適用于 router-link 組件的 to 屬性。
總結(jié):
params 傳參,push 里面只能是 name:’xxx’,不能是 path:’/xxx’,因?yàn)?params 只能用 name 來引入路由,如果這里寫成了 path ,接收參數(shù)頁面會是 undefined。
路由傳參的方式:
1、手寫完整的 path:
this.$router.push({path: `/user/${userId}`});
獲取參數(shù):this.$route.params.userId
2、用 params 傳遞:
this.$router.push({name:’user’, params:{userId: ’123’}});
獲取參數(shù):this.$route.params.userId
url 形式:url 不帶參數(shù),http:localhost:8080/#/user
3、用 query 傳遞:
this.$router.push({path:’/user’, query:{userId: ’123’}});
獲取參數(shù):this.$route.query.userId
url 形式:url 帶參數(shù),http:localhost:8080/#/user?userId=123
直白的說,query 相當(dāng)于 get 請求,頁面跳轉(zhuǎn)的時(shí)候可以在地址欄看到請求參數(shù),params 相當(dāng)于 post 請求,參數(shù)不在地址欄中顯示。
要注意,以 / 開頭的嵌套路徑會被當(dāng)作根路徑。 這讓你充分的使用嵌套組件而無須設(shè)置嵌套的路徑。
總結(jié)
到此這篇關(guān)于Vue中this.$router和this.$route的區(qū)別及push()方法的文章就介紹到這了,更多相關(guān)Vue中this.$router和this.$route區(qū)別內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. vue+vuex+axios從后臺獲取數(shù)據(jù)存入vuex,組件之間共享數(shù)據(jù)操作2. android studio實(shí)現(xiàn)簡單的計(jì)算器(無bug)3. springboot項(xiàng)目整合druid數(shù)據(jù)庫連接池的實(shí)現(xiàn)4. Python 忽略文件名編碼的方法5. android 控件同時(shí)監(jiān)聽單擊和雙擊實(shí)例6. JavaScript實(shí)現(xiàn)簡易計(jì)算器小功能7. SpringBoot使用Captcha生成驗(yàn)證碼8. 解決vue頁面刷新,數(shù)據(jù)丟失的問題9. python 讀txt文件,按‘,’分割每行數(shù)據(jù)操作10. python logging.info在終端沒輸出的解決
