參數傳遞
我們經常需要把某種模式匹配到的所有路由,全都映射到同個組件。例如,我們有一個 User 組件,對於所有 ID 各不相同的用戶,都要使用這個組件來渲染。此時我們就需要傳遞參數了;
使用路徑匹配的方式
- 修改路由配置,主要是在
path
屬性中增加了:id
這樣的占位符
{path: '/user/profile/:id', name:'UserProfile', component: UserProfile}
router-link
方式傳遞
<router-link :to="{name: 'UserProfile', params: {id: 1}}">個人信息</router-link>
注意: 此時我們將 to
改為了 :to
,是為了將這一屬性當成對象(Model)使用,注意 router-link 中的 name 屬性名稱 一定要和 路由中的 name 屬性名稱 匹配,因為這樣 Vue 才能找到對應的路由路徑;
- 代碼方式傳遞
this.$router.push({ name: 'UserProfile', params: {id: 1}});
- 在目標組件中使用以下方式接收參數
{{ $route.params.id }}
使用 props 的方式
- 修改路由配置,主要增加了
props: true
屬性
{path: '/user/profile/:id', name:'UserProfile', component: UserProfile, props: true}
router-link
方式傳遞
<router-link :to="{name: 'UserProfile', params: {id: 1}}">個人信息</router-link>
- 代碼方式傳遞
this.$router.push({ name: 'UserProfile', params: {id: 1}});
- 接收參數,為目標組件增加
props
屬性
export default { props: ['id'], name: "UserProfile" }
- 模板中使用接收參數
{{ id }}
重定向
重定向的意思大家都明白,但 Vue 中的重定向是作用在路徑不同但組件相同的情況下
修改路由配置
{ path: '/main', name: 'Main', component: Main }, { path: '/goHome', redirect: '/main' }
說明:這里定義了兩個路徑,一個是 /main
,一個是 /goHome
,其中 /goHome
重定向到了 /main
路徑,由此可以看出重定向不需要定義組件;
重定向到組件
設置對應路徑即可
<router-link to="/goHome">回到首頁</router-link>
帶參數的重定向
- 修改路由配置
{ // 首頁 path: '/main/:username', name: 'Main', component: Main }, { path: '/goHome/:username', redirect: '/main/:username' }
- 重定向到組件
<router-link to="/goHome/Lusifer">回到首頁</router-link>