vue中路由跳轉的方式有哪些你知道嗎
阿新 • • 發佈:2021-11-17
目錄
- 第一種方式:router-link (宣告式路由)
- 第二種方式:router.push(式路由)
- 第三種方式:this.$router.push() (函式裡面呼叫)
- 第四種方式:this.$router.replace() (用法同上,push)
- 參考:
- 總結
第一種方式:router-link (宣告式路由)
1. 不帶引數 <router-link :to="{name:'home'}"> <router-link :to="{path:'/home'}"> //name,path都行,建議用name // 注意:router-link中連結如果是'/'開始就是從根路由開始,如果開始不帶'/',則從當前路由開始。 2.帶引數 <router-link :to="{name:'home',params: {id:1}}"> // params傳引數 (類似post) // 路由配置 path: "/home/:id" 或者 path: "/home:id"// 不配置path,第一次可請求,重新整理頁面id會消失 // 配置path,重新整理頁面id會保留 // html 取參 $route.params.id // script 取參 this.$route.params.id <router-link :to="{name:'home',query: {id:1}}">
第二種方式:router.push(程式設計式路由)
// 字串 router.push('home') // 物件 router.push({ path: 'home' }) // 命名的路由 router.push({ name: 'user',params: { userId: '123' }}) // 帶查詢引數,變成 /register?plan=private router.push({ path: 'register',query: { plan: 'private' }})
注意:如果提供了 path,params 會被忽略,上述例子中的 query 並不屬於這種情況。取而代之的是下面例子的做法,你需要提供路由的 name 或手寫完整的帶有引數的 path:
const userId = '123' router.push({ name: 'user',params: { userId }}) // -> /user/123 router.push({ path: `/user/${userId}` }) // -> /user/123 // 這裡的 params 不生效 router.push({ path: '/user',params: { userId }}) // -> /user
第三種方式:this.$router.push() (函式裡面呼叫)
1. 不帶引數 this.$router.push('/home') this.$router.push({name:'home'}) this.$router.push({path:'/home'}) 2. query傳參 this.$router.push({name:'home',query: {id:'1'}}) this.$router.push({path:'/home',query: {id:'1'}}) // html 取參 $route.query.id // script 取參 this.$route.query.id 3. params傳參 this.$router.push({name:'home',params: {id:'1'}}) // 只能用 name // 路由配置 path: "/home/:id" 或者 path: "/home:id",// 不配置path,重新整理頁面id會保留 // html 取參 $route.params.id // script 取參 this.$route.params.id 4. query和params區別 query類似 get,跳轉之後頁面 url後面會拼接引數,類似?id=1,非重要性的可以這樣傳,密碼之類還是用params重新整理頁面id還在 params類似 post,跳轉之後頁面 url後面不會拼接引數,但是重新整理頁面id 會消失 **注意:獲取路由上面的引數,用的是$route,後面沒有r**
第四種方式:this.$router.replace() (用法同上,push)
第五種方式:this.$router.go(n)
this.$router.go(n) 向前或者向後跳轉n個頁面,n可為正整數或負整數 ps : 區別 this.$rohttp://www.cppcns.comuter.push 跳轉到指定url路徑,並想history棧中新增一個記錄,點選後退會返回到上一個頁面 this.$router.replace 跳轉到指定url路徑,但是history棧中不會有記錄,點選返回會跳轉到上上個頁面 (就是直接替換了當前頁面) this.$router.go(n) 向前或者向後跳轉n個頁面,n可為正整數或負整數
params是路由的一部分,必須要有。query是拼接在url後面的引數,沒有也沒關係。
params一旦設定在路由,params就是路由的一部分,如果這個路由有params傳參,但是在跳轉的時候沒有傳這個引數,會導致跳轉失敗或者頁面會沒有內容。
params、query不設定也可以傳參,但是params不設定的時候,重新整理頁面或者返回引數會丟失,
兩者都可以傳遞引數,區別是什麼?
query 傳參配置的是path,而params傳參配置的是name,在params中配置path無效
query在路http://www.cppcns.com由配置不需要設定引數,而params必須設定
query傳遞的引數會顯示在位址列中
params傳參重新整理會無效,但是query會儲存傳遞過來的值,重新整理不變
參考:
https://www.jb51.net/article/183611.htm
. 官網
總結
本篇文章就到這裡了,希望能夠給你帶來幫助,也希望您能夠多http://www.cppcns.com多關注我們的更多內容!