vue路由傳參按照傳參方式可劃分為params傳參和query傳參; params傳參分為在url中顯示和影藏參數(shù)兩種方式
1 params傳參(url地址欄顯示參數(shù))
1.1 聲明式 router-link
通過(guò)router-link的to屬性實(shí)現(xiàn),該方法的參數(shù)可以是一個(gè)字符串;使用該方式時(shí),需要子路由中提前配置好參數(shù),如:
// 1 路由配置
{
path: 'content/:id',
name: 'Content',
component: Content,
},
// 2 頁(yè)面跳轉(zhuǎn)
<router-link :to="'content/123'">進(jìn)入</router-link>
// 3 獲取方式
this.$route.params.id // 輸出123
1.2 編程式 this.$router.push
使用該方式傳參時(shí),需要在路由中提前配置好參數(shù), 如:
// 1 路由配置
{
path: 'content/:id',
name: 'Content',
component: Content,
},
// 2 頁(yè)面觸發(fā)js事件
linkTo() {
// 此處參數(shù)456可以通過(guò)動(dòng)態(tài)變量替換
this.$router.push('content/456') ;
// 或
this.$router.push({path: 'content/456'}) ;
},
// 3 參數(shù)獲取方式
this.$route.params.id // 輸出456
url地址欄展示:

params傳參url展示參數(shù).png
2 params傳參(url地址欄不顯示參數(shù))
params(不顯示傳參)也可以分為聲明式和編程式兩種,與方式一不同的是通過(guò)name進(jìn)行傳參,實(shí)現(xiàn)跳轉(zhuǎn);
2.1 聲明式router-link
通過(guò)router-link組件的to屬性實(shí)現(xiàn)
// 1 路由配置
{
path: 'content',
name: 'Content',
component: Content,
},
// 2 頁(yè)面跳轉(zhuǎn)
<router-link :to="{name: 'Content', params: {id: 123}}">進(jìn)入</router-link>
// 3 參數(shù)獲取
this.$route.params.id // 輸出123
2.2 編程式this.$router.push
使用該方式傳值時(shí),需要在路由中提前配置好參數(shù),不過(guò)不需要在使用":/id"等類似方式傳遞參數(shù),具體如下:
// 1 路由配置
{
path: 'content',
name: 'Content',
component: Content,
}
// 2 js實(shí)現(xiàn)路由跳轉(zhuǎn)
this.$router.push({
name: 'Content',
params: {
id: 123
}
})
// 3 參數(shù)獲取
this.$route.params.id // 顯示undefined
注意: 上述這種利用params不顯示url傳參的方式會(huì)導(dǎo)致在刷新頁(yè)面的時(shí)候,傳遞的值會(huì)丟失;
3 query傳參(顯示參數(shù))
query傳參(顯示參數(shù))也可分為聲明式和編程式兩種方式
3.1 聲明式 router-link
通過(guò)router-link組件的to屬性實(shí)現(xiàn),不過(guò)該方式傳值的時(shí)候,需要子路由提前配置好路由別名(name屬性),如
// 1 路由配置
{
path: 'content',
name: 'Content',
component: Content,
}
// 2 頁(yè)面設(shè)置
<router-link :to="{name: 'Content', query: {id: 123}}">進(jìn)入</router-link>
// 3 參數(shù)獲取
this.$route.query.id // 輸出 123
3.2 編程式 this.$router.push
使用該方式傳值的時(shí)候,需要路由提前配置好路由別名(name屬性), 如:
// 1 路由配置
{
path: 'content',
name: 'Content',
component: Content,
}
// 2 js跳轉(zhuǎn)
this.$router.push({
name: 'Content',
query: {
id: 123
}
})
// 3 參數(shù)獲取
this.$route.query.id // 輸出123
url地址欄展示:

query方式url展示.png