vue路由傳參方式的方式總結(jié)及獲取參數(shù)詳解
一、聲明式傳參
1.params傳參(顯示參數(shù))
在url中會(huì)顯示出傳參的值,刷新頁(yè)面不會(huì)失去拿到的參數(shù),使用該方式傳值的時(shí)候,需要子路由提前配置好參數(shù):
//路由參數(shù)配置
const router = new VueRouter({
routes: [{
path: '/about/:id',
component: User
}]
})
//聲明式導(dǎo)航使用
<router-link to="/about/12">跳轉(zhuǎn)</router-link>//路由參數(shù)配置
const router = new VueRouter({
routes: [{
name: 'user1',
path: '/about/:id',
component: User
}]
})
//聲明式導(dǎo)航使用
<router-link :to="{ name: 'user1', params: { id: 123 } }">跳轉(zhuǎn)</router-link>2.params傳參(不顯示參數(shù))
在url中不會(huì)顯示出傳參的值,但刷新頁(yè)面會(huì)失去拿到的參數(shù),使用該方式 傳值 的時(shí)候,需要子路由提前配置好name參數(shù):
//路由參數(shù)配置
const router = new VueRouter({
routes: [{
name: 'user1',
path: '/about',
component: User
}]
})
//聲明式導(dǎo)航使用
<router-link :to="{ name: 'user1', params: { id: 123 } }">跳轉(zhuǎn)</router-link>3.query 傳參
query 傳過(guò)去的參數(shù)會(huì)拼接在地址欄中(?name=xx),刷新頁(yè)面數(shù)據(jù)不會(huì)丟失,使用path和name都可以:
//路由參數(shù)配置
const router = new VueRouter({
routes: [{
name: 'user1',
path: '/about',
component: User
}]
})
//使用name
<router-link :to="{ name: 'user1', query: { id: 123 }}"></router-link>
//使用path
<router-link :to="{ path: '/about', query: { id: 123 } }"></router-link>二、編程式傳參
1.params傳參(顯示參數(shù))
//路由配置
{
path: '/child/:id',
component: Child
}
//編程式使用
this.$router.push({
path:'/child/${id}',
})//路由配置
{
path: '/child:id',
component: Child,
name:Child
}
//編程式使用
this.$router.push({
name:'Child',
params:{
id:123
}
})2.params傳參(不顯示參數(shù))
//路由配置
{
path: '/child',
component: Child,
name:Child
}
//編程式使用
this.$router.push({
name:'Child',
params:{
id:123
}
})3.query 傳參
//路由配置
{
path: '/child',
component: Child,
name:Child
}
//編程式使用
//name方式
this.$router.push({
name:'Child',
query:{
id:1
}
})
//path方式
this.$router.push({
path:'/child',
query:{
id:1
}
})
三、獲取參數(shù)
1、params的獲取方式
this.$route.params.xxx
2、query的獲取方式
this.$route.query.xxx
四、需要注意的點(diǎn)
1、如果使用params傳參,且參數(shù)是以對(duì)象的形式,跳轉(zhuǎn)路徑只能使用name形式而不能用path.
2、如果想要params參數(shù)想傳參也可以不傳參需要在占位符后面加?。
//路由參數(shù)配置
const router = new VueRouter({
routes: [{
path: '/search/:keyword?',
name: 'search',
component: () => import('@/pages/Search'),
meta: { show: true }
}]
})
//編程式傳參
this.$router.push({
name: "search",
params: {},
query: { keyword: this.keyword },
});3、解決params傳值為空字符串路徑會(huì)出現(xiàn)問(wèn)題:
this.$router.push({
name: "search",
params: { keyword: "" || undefined },
query: { keyword: this.keyword },
});總結(jié)
到此這篇關(guān)于vue路由傳參方式的方式總結(jié)及獲取參數(shù)的文章就介紹到這了,更多相關(guān)vue路由傳參及獲取參數(shù)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Vue實(shí)現(xiàn)封裝樹(shù)狀圖的示例代碼
這篇文章主要為大家詳細(xì)介紹了如何使用Vue實(shí)現(xiàn)封裝樹(shù)狀圖,文中的示例代碼講解詳細(xì),具有一定的借鑒價(jià)值,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2024-03-03
vue頁(yè)面中使用getElementsByClassName無(wú)法獲取元素的解決
這篇文章主要介紹了vue頁(yè)面中使用getElementsByClassName無(wú)法獲取元素的解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-03-03

