vue-router傳遞參數(shù)的幾種方式實例詳解
vue-router傳遞參數(shù)分為兩大類
- 編程式的導(dǎo)航 router.push
- 聲明式的導(dǎo)航 <router-link>
編程式的導(dǎo)航 router.push
編程式導(dǎo)航傳遞參數(shù)有兩種類型:字符串、對象。
字符串
字符串的方式是直接將路由地址以字符串的方式來跳轉(zhuǎn),這種方式很簡單但是不能傳遞參數(shù):
this.$router.push("home");
對象
想要傳遞參數(shù)主要就是以對象的方式來寫,分為兩種方式:命名路由、查詢參數(shù),下面分別說明兩種方式的用法和注意事項。
命名路由
命名路由的前提就是在注冊路由的地方需要給路由命名如:
命名路由傳遞參數(shù)需要使用params來傳遞,這里一定要注意使用params不是query。
目標頁面接收傳遞參數(shù)時使用params
特別注意:命名路由這種方式傳遞的參數(shù),如果在目標頁面刷新是會出錯的
使用方法如下:
this.$router.push({ name: 'news', params: { userId: 123 }})
代碼如下:
<template> <div class="hello"> <h1>{{ msg }}</h1> <button @click="routerTo">click here to news page</button> </div> </template> <script> export default { name: 'HelloWorld', data () { return { msg: 'Welcome to Your Vue.js App' } }, methods:{ routerTo(){ this.$router.push({ name: 'news', params: { userId: 123 }}); } } } </script> <style> </style>接受傳遞的參數(shù):<template> <div> this is the news page.the transform param is {{this.$route.params.userId}} </div> </template> <script> </script>
運行效果如下:
查詢參數(shù)
查詢參數(shù)其實就是在路由地址后面帶上參數(shù)和傳統(tǒng)的url參數(shù)一致的,傳遞參數(shù)使用query而且必須配合path來傳遞參數(shù)而不能用name,目標頁面接收傳遞的參數(shù)使用query。
注意:和name配對的是params,和path配對的是query
使用方法如下:
this.$router.push({ path: '/news', query: { userId: 123 }});代碼如下:<template> <div class="hello"> <h1>{{ msg }}</h1> <button @click="routerTo">click here to news page</button> </div> </template> <script> export default { name: 'HelloWorld', data () { return { msg: 'Welcome to Your Vue.js App' } }, methods:{ routerTo(){ this.$router.push({ path: '/news', query: { userId: 123 }}); } } } </script> <style> </style>接收參數(shù)如下:<template> <div> this is the news page.the transform param is {{this.$route.query.userId}} </div> </template> <script> </script>
運行效果如下:
聲明式的導(dǎo)航
聲明式的導(dǎo)航和編程式的一樣,這里就不在過多介紹,給幾個例子大家對照編程式理解,
例子如下:
字符串
<router-link to="news">click to news page</router-link>
命名路由
<router-link :to="{ name: 'news', params: { userId: 1111}}">click to news page</router-link>
運行效果如下:
查詢參數(shù)
<router-link :to="{ path: '/news', query: { userId: 1111}}">click to news page</router-link>
運行效果如下:
最后總結(jié):
路由傳遞參數(shù)和傳統(tǒng)傳遞參數(shù)是一樣的,命名路由類似表單提交而查詢就是url傳遞,在vue項目中基本上掌握了這兩種傳遞參數(shù)就能應(yīng)付大部分應(yīng)用了,最后總結(jié)為以下兩點:
1.命名路由搭配params,刷新頁面參數(shù)會丟失
2.查詢參數(shù)搭配query,刷新頁面數(shù)據(jù)不會丟失
3.接受參數(shù)使用this.$router后面就是搭配路由的名稱就能獲取到參數(shù)的值
總結(jié)
以上所述是小編給大家介紹的vue-router傳遞參數(shù)的幾種方式實例詳解,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
相關(guān)文章
使用element-ui table expand展開行實現(xiàn)手風琴效果
這篇文章主要介紹了使用element-ui table expand展開行實現(xiàn)手風琴效果,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習或者工作具有一定的參考學(xué)習價值,需要的朋友們下面隨著小編來一起學(xué)習學(xué)習吧2019-03-03解決vscode進行vue格式化,會自動補分號和雙引號的問題
這篇文章主要介紹了解決vscode進行vue格式化,會自動補分號和雙引號的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-10-10