在我們開發vue項目的時候,路由傳參幾乎是我們必須要用到的,一般出現場景是,當我們點擊某個組件的某個按鈕時跳轉到另一個組件中,並攜帶參數,便於第二個組件獲取數據。下面我就來說說vue路由傳參的三種方式:
方案一:
getDescribe(id) {
// 直接調用$router.push 實現攜帶參數的跳轉
this.$router.push({
path: `/describe/${id}`,
})
方案一需要配置的對應路由如下:
{
path: '/describe/:id',
name: 'Describe',
component: Describe
}
很顯然,需要在path中添加/:id來對應 $router.push 中path攜帶的參數。在子組件中可以使用來獲取傳遞的參數值。
切記是用 params 方法來獲取,不是用 query 來獲取
this.$route.params.id
方案二:
在第一個組件中,通過路由屬性中的name來確定匹配的路由,通過params來傳遞參數。
this.$router.push({
name: 'Describe',
params: {
id: id
}
})
對應路由配置: 這裏可以添加:/id 也可以不添加,添加數據會在url後面顯示,不添加數據就不會顯示
{ // 這就是沒添加的情況
path: '/describe',
name: 'Describe',
component: Describe
}
第二個組件中:這樣來獲取參數
this.$route.params.id
方案三:
第一個組件:使用path來匹配路由,然後通過query來傳遞參數
這種情況下 query傳遞的參數會顯示在url後面?id=?
this.$router.push({
path: '/describe',
query: {
id: id
}
})
對應路由配置:
{
path: '/describe',
name: 'Describe',
component: Describe
}
第二個組件: 這樣來獲取參數
this.$route.query.id