我們經常需要把某種模式匹配到的所有路由,全都映射到同個組件。例如,我們有一個 User 組件,對於所有 ID 各不相同的用戶,都要使用這個組件來渲染。那么,我們可以在 vue-router 的路由路徑中使用“動態路徑參數”來達到這個效果:
1. 編程式導航
[ User.vue ]:觸發事件動態傳參並跳轉至相應路由
<li v-for="(item,index) in userList" :key="item.id" @click="showTable(item.id)">點擊跳轉至用戶詳情頁</li> showTable (id) { this.$router.push({ name: 'user', params: { id: id } }) }
[ router.js ]:
const router = new VueRouter({ routes: [ // 動態路徑參數 以冒號開頭 { path: '/user/:id',
name: 'user',
component: User
//components: {
// default: () => import('./components/User.vue')
//},
}
]
})
編程式導航傳遞參數有兩種類型:字符串、對象。
// 字符串 this.$router.push('user')
// 對象 this.$router.push({ path: 'user' }) // 命名的路由,變成 /user/id/edward this.$router.push({ name: 'user', params: { id: 'edward' }}) // 帶查詢參數,變成 /user?id=edward this.$router.push({ path: 'user', query: { id: 'edward' }})
根據動態參數 id 展示詳情UI:
點擊跳轉至相應的路由頁面后,如果想要渲染UI界面,需要通過this.$route.params.id 或 this.$route.query.id 的方式獲取參數,從而向后台請求相應的數據:
const { id } = this.$route.params
axios.get(`http://www.edward.com/detail?id=${id}`).then(res =>{
this.name= res.name
this.age = res.age
})
在編程式導航時,如果連續幾次觸發路由導航,相當於在路由中添加了相同的路由,會報錯:
"Navigating to current location ("/nav/form") is not allowed",
【解決方法】:在引用過vue-router的文件當中加上如下代碼:
import Vue from 'vue' import Router from 'vue-router' Vue.use(Router) const VueRouterPush = Router.prototype.push Router.prototype.push = function push (to) { return VueRouterPush.call(this, to).catch(err => err) }
2. 聲明式導航
[ User.vue ]:觸發事件動態傳參並跳轉至相應路由
// 寫法一:
<router-link tag="li" :to="{ path: `/user/${id}` }" v-for="(item,index) in userList" :key="index">點擊跳轉至用戶詳情頁</router-link>
// 寫法二:
<router-link tag="li" :to="{ name: 'user', params: { id: item.id } }" v-for="(item,index) in userList" :key="index">點擊跳轉至用戶詳情頁</router-link>
// 寫法三:查詢路由方式
<router-link tag="li" :to="{ path: '/user', query: { id: item.id } }" v-for="(item,index) in userList" :key="index">點擊跳轉至用戶詳情頁</router-link>
1.命名路由搭配params,刷新頁面參數會丟失
2.查詢參數搭配query,刷新頁面數據不會丟失
[ router.js ]:(同上)
