官網:嵌套路由
同時也請參考昨日有出現的:搞搞就懂
在官網可以看到第一張示意圖,是一個固定user,只切換profile跟post的情境。現在來試做這個情境:
1.依照前天文章建立初始專案的步驟(init),直接從第五點開始,其他都一樣
2.依照昨天文章步驟建立router,把HelloWorld.vue改成User.vue,index.js裡import跟export也要記得改唷!還有App.vue裡面也要改
3.User.vue的template內容刪改成剩下這樣:
<template>
<div>
<h1>這是User</h1>
<router-view></router-view>
</div>
</template>
4.在components資料夾下新增一個user-components資料夾,命名用dash我不確定好不好,不過先暫時這樣做,但我知道這裡會習慣用複數來命名資料夾名稱。資料夾底下我們複製User.vue貼過來,改名為Post.vue跟Profile.vue,兩個檔案裡面的<template><h1>內容也改成<h1>這是Post</h1>跟<h1>這是Profile</h1>
5.回到index.js,import&export routes增加children,值的型別為陣列:
import Post from '@/components/user-components/post'
import Profile from '@/components/user-components/profile'
export default new VueRouter({
routes: [{
name: 'User',
path: '/user',
component: User,
children: [{ //從這裡開始
name: 'Post',
path: 'post',
component: Post,
},
{
name: 'Profile',
path: 'profile',
component: Profile,
},
]
}],
});
6.路由更動後,終端機重啟 npm run dev,開啟網頁後在網址列#後面輸入user-components/profile及user-components/post看看有沒有成功
簡單來說是可以在路由系統內取代<a>的方便工具,如要嵌入外部連結還是乖乖用<a>。
直接看程式碼:回到User.vue,裡面的template內容增加兩行,改成這樣:
<template>
<div>
<h1>這是User</h1>
<router-link :to="{ name:'Post' }">Post</router-link>
<router-link :to="{ name:'Profile' }">Profile</router-link>
<router-view></router-view>
</div>
</template>
然後開啟網頁看看有沒有跑出這兩個連結,點擊後會很聰明的自動幫我們連到該頁面。這裡的 name:'...'就是寫在component: User後面巢狀路由裡各自的name,真是很人性化的寫法~
以上步驟為筆者實作後的整理,如有卡關的地方可以開啟開發者工具> vue檢視。筆者第一個卡的地方是忘了在main.js new Vew裡面放入router,鐵則果然是任何的程式學習都要親自操作才會進步得快!