To-Do Calendar - Day6 登入驗證與 Vue Router 配置
首頁畫面刻好後,這篇進入到登入功能開發了~
紀錄一下 Bootstrap 排版心得:justify-content 指的是主軸對齊,align-items 是交錯軸對齊,而主軸的方向可以透過 .flex-row、.flex-row-reverse、.flex-column、flex-column-reverse,將軸線水平反轉或轉為垂直、垂直反轉等,所以 首頁 登入 註冊 內頁justify-content-end
不一定就是置右,align-items-center
也不一定就是垂直置中,視交錯軸的方向也可以是水平置中。
目前畫面的進度:
登入流程
- 這次跟以往做得不太一樣,沒有登入頁,初次進入首頁後要點 Get started 按鈕才會開啟登入 Modal,點切換到註冊連結會開啟註冊 Modal。登入或註冊後會直接進到內頁(預設是代辦事項頁)。
- 點 Get started 按鈕時會先經過登入狀態判斷,如果是登入中就可以直接進到內頁,跳過登入的步驟。
- 內頁必須登入後才能訪問,如果使用者直接輸入指定內頁網址,要攔截導向回首頁,並自動開啟登入 Modal。
做法
從首頁進到內頁
把 Get started 按鈕的 data-target 屬性拿掉,改用 @click 的方式,先檢查登入狀態,再決定是開啟登入 Modal 還是直接進到內頁。
從首頁進到內頁(未登入) 從首頁進到內頁(已登入)
輸入指定網址進到內頁
路由 meta 資料
在需要登入後才能訪問的頁面上,新增 meta 資料 requiresAuth: true
屬性。
(按照課程範例,router.beforeEach Hook 是放在 main.js,但是我想將 router 相關程式碼都放在同一支,這裡有做一點修改,把原先的 export default new VueRouter 改為 const router = new VueRouter,加上 router.beforeEach Hook 後,最後再匯出到 main.js)
const router = new VueRouter({
linkActiveClass: "active",
routes: [
{
path: "*", //防止使用者在網站網址後面輸入任意文字進到空白頁面
redirect: "/",
},
{
name: "index",
path: "/",
component: Index,
},
{
name: "innerPage",
path: "/innerPage",
component: InnerPage,
meta: {
requireAuth: true,
},
children: [
{
name: "todoLists",
path: "todoLists",
component: TodoLists,
meta: {
requireAuth: true,
},
},
{
name: "habitTracker",
path: "habitTracker",
component: HabitTracker,
meta: {
requireAuth: true,
},
},
{
name: "notes",
path: "notes",
component: Notes,
meta: {
requireAuth: true,
},
},
],
},
],
});
攔截路由檢查
router.beforeEach 會在切換頁面時觸發,加上 meta.requireAuth 的判斷式,當路由有設定 meta 資料 requiresAuth: true
,就會被攔截下來驗證登入狀態,登入中才會放行到指定頁面,未登入則導回首頁,讓使用者重新登入。
router.beforeEach 分別有3個參數
to:即將要轉跳的頁面
from:從哪個頁面轉過來
next:執行下一個事件Warningrouter.beforeEach 中每個判斷都必須確保使用到 next()。
router.beforeEach((to, from, next) => {
if (to.meta.requireAuth) {
if ( 驗證成功 ) { //待實作Vuex
next();
} else {
next({
path: "/"
});
}
} else {
next();
}
});
防止未登入訪問特定頁面 防止輸入任意文字進到空白內頁
下一篇再來介紹 Vuex 的使用~