原文:https://www.cnblogs.com/EnSnail/p/8458001.html
路由是連接各個頁面的橋梁,而參數(shù)在其中扮演者異常重要的角色,在一定意義上,決定著兩座橋梁是否能夠連接成功。
在vue路由中,支持3中傳參方式。
場景,點擊父組件的li元素跳轉(zhuǎn)到子組件中,并攜帶參數(shù),便于子組件獲取對應li的數(shù)據(jù),顯示相應的正確的內(nèi)容。
父組件中:
<li v-for="article in articles" @click="getDescribe(article.id)">
方案一:
getDescribe(id) {// 直接調(diào)用$router.push 實現(xiàn)攜帶參數(shù)的跳轉(zhuǎn)this.$router.push({
? ? ? ? ? path: `/describe/${id}`,
? ? ? ? })// 方案一,需要對應路由配置如下:? {
? ? path: '/describe/:id',
? ? name: 'Describe',
? ? component: Describe
? }// 很顯然,需要在path中添加/:id來對應 $router.push 中path攜帶的參數(shù)。// 在子組件中可以使用來獲取傳遞的參數(shù)值。$route.params.id
方案二:
// 父組件中:通過路由屬性中的name來確定匹配的路由,通過params來傳遞參數(shù)。this.$router.push({
? ? ? ? ? name: 'Describe',
? ? ? ? ? params: {
? ? ? ? ? ? id: id
? ? ? ? ? }
? ? ? ? })// 對應路由配置: 注意這里不能使用:/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
? ? ? ? ? }
? ? ? ? })// 對應路由配置:? {
? ? path: '/describe',
? ? name: 'Describe',
? ? component: Describe
? }// 對應子組件: 這樣來獲取參數(shù)$route.query.id// 這里要特別注意 在子組件中 獲取參數(shù)的時候是$route.params 而不是$router 這很重要~~~