現(xiàn)有如下場景衷佃,點擊父組件的li元素跳轉(zhuǎn)到子組件中锌历,并攜帶參數(shù)鼎俘,便于子組件獲取數(shù)據(jù)。
父組件中:
<li v-for="article in articles" @click="getDescribe(article.id)">
methods:
方案一:
getDescribe(id) {
// 直接調(diào)用$router.push 實現(xiàn)攜帶參數(shù)的跳轉(zhuǎn)
this.$router.push({
path: `/describe/${id}`,
})
方案一辩涝,需要對應(yīng)路由配置如下:
{
path: '/describe/:id',
name: 'Describe',
component: Describe
}
很顯然贸伐,需要在path中添加/:id來對應(yīng) $router.push 中path攜帶的參數(shù)。在子組件中可以使用來獲取傳遞的參數(shù)值怔揩。
$route.params.id
方案二:
父組件中:通過路由屬性中的name來確定匹配的路由捉邢,通過params來傳遞參數(shù)脯丝。
this.$router.push({
name: 'Describe',
params: {
id: id
}
})
對應(yīng)路由配置: 注意這里不能使用:/id來傳遞參數(shù)了,因為父組件中伏伐,已經(jīng)使用params來攜帶參數(shù)了宠进。
{
path: '/describe',
name: 'Describe',
component: Describe
}
子組件中: 這樣來獲取參數(shù)
$route.params.id
方案三:
父組件:使用path來匹配路由,然后通過query來傳遞參數(shù)
這種情況下 query傳遞的參數(shù)會顯示在url后面?id=藐翎?
this.$router.push({
path: '/describe',
query: {
id: id
}
})
對應(yīng)路由配置:
{
path: '/describe',
name: 'Describe',
component: Describe
}
對應(yīng)子組件: 這樣來獲取參數(shù)
$route.query.id
這里要特別注意 在子組件中 獲取參數(shù)的時候是$route.params 而不是
$router 這很重要~~~