vue路由傳參按照傳參方式可劃分為params傳參和query傳參; params傳參分為在url中顯示和影藏參數兩種方式
1 params傳參(url地址欄顯示參數)1.1 聲明式 router-link通過router-link的to屬性實現,該方法的參數可以是一個字符串;使用該方式時,需要子路由中提前配置好參數,如:
// 1 路由配置
{
path: 'content/:id',
name: 'Content',
component: Content,
},
// 2 頁面跳轉
<router-link :to="'content/123'">進入</router-link>
// 3 獲取方式
this.$route.params.id // 輸出123
使用該方式傳參時,需要在路由中提前配置好參數, 如:
// 1 路由配置
{
path: 'content/:id',
name: 'Content',
component: Content,
},
// 2 頁面觸發js事件
linkTo() {
// 此處參數456可以通過動态變量替換
this.$router.push('content/456') ;
// 或
this.$router.push({path: 'content/456'}) ;
},
// 3 參數獲取方式
this.$route.params.id // 輸出456
url地址欄展示:
params傳參url展示參數.png
2 params傳參(url地址欄不顯示參數)params(不顯示傳參)也可以分為聲明式和編程式兩種,與方式一不同的是通過name進行傳參,實現跳轉;
2.1 聲明式router-link通過router-link組件的to屬性實現
// 1 路由配置
{
path: 'content',
name: 'Content',
component: Content,
},
// 2 頁面跳轉
<router-link :to="{name: 'Content', params: {id: 123}}">進入</router-link>
// 3 參數獲取
this.$route.params.id // 輸出123
使用該方式傳值時,需要在路由中提前配置好參數,不過不需要在使用":/id"等類似方式傳遞參數,具體如下:
// 1 路由配置
{
path: 'content',
name: 'Content',
component: Content,
}
// 2 js實現路由跳轉
this.$router.push({
name: 'Content',
params: {
id: 123
}
})
// 3 參數獲取
this.$route.params.id // 顯示undefined
注意: 上述這種利用params不顯示url傳參的方式會導緻在刷新頁面的時候,傳遞的值會丢失;
3 query傳參(顯示參數)query傳參(顯示參數)也可分為聲明式和編程式兩種方式
3.1 聲明式 router-link通過router-link組件的to屬性實現,不過該方式傳值的時候,需要子路由提前配置好路由别名(name屬性),如
// 1 路由配置
{
path: 'content',
name: 'Content',
component: Content,
}
// 2 頁面設置
<router-link :to="{name: 'Content', query: {id: 123}}">進入</router-link>
// 3 參數獲取
this.$route.query.id // 輸出 123
使用該方式傳值的時候,需要路由提前配置好路由别名(name屬性), 如:
// 1 路由配置
{
path: 'content',
name: 'Content',
component: Content,
}
// 2 js跳轉
this.$router.push({
name: 'Content',
query: {
id: 123
}
})
// 3 參數獲取
this.$route.query.id // 輸出123
url地址欄展示:
query方式url展示.png
,更多精彩资讯请关注tft每日頭條,我们将持续为您更新最新资讯!