路由是連接各個頁面的橋梁,而參數在其中扮演者異常重要的角色,在一定意義上,決定着兩座橋梁是否能夠連接成功。
在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 這很重要~~~