路由是連接各個頁面的橋梁,而參數在其中扮演者異常重要的角色,在一定意義上,決定著兩座橋梁是否能夠連接成功。
在vue路由中,支持3中傳參方式。
場景,點擊父組件的li元素跳轉到子組件中,并攜帶參數,便于子組件獲取對應li的數據,顯示相應的正確的內容。
父組件中:
<li v-for="article in articles" @click="getDescribe(article.id)">
方案一:
getDescribe(id) {// 直接調用$router.push 實現攜帶參數的跳轉 this.$router.push({ path: `/describe/${id}`, })// 方案一,需要對應路由配置如下: { path: '/describe/:id', name: 'Describe', component: Describe }// 很顯然,需要在path中添加/:id來對應 $router.push 中path攜帶的參數。// 在子組件中可以使用來獲取傳遞的參數值。$route.params.id方案二:
// 父組件中:通過路由屬性中的name來確定匹配的路由,通過params來傳遞參數。 this.$router.push({ name: 'Describe', params: { id: id } })// 對應路由配置: 注意這里不能使用:/id來傳遞參數了,因為父組件中,已經使用params來攜帶參數了。 { path: '/describe', name: 'Describe', component: Describe }//子組件中: 這樣來獲取參數$route.params.id方案三:
// 父組件:使用path來匹配路由,然后通過query來傳遞參數這種情況下 query傳遞的參數會顯示在url后面?id=? this.$router.push({ path: '/describe', query: { id: id } })// 對應路由配置: { path: '/describe', name: 'Describe', component: Describe }// 對應子組件: 這樣來獲取參數$route.query.id// 這里要特別注意 在子組件中 獲取參數的時候是$route.params 而不是$router 這很重要~~~以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答