vue 路由傳參的三種基本模式

原文: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 這很重要~~~

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。