0%

Vue3TypeScript(6) - 實現路由守衛

1. 實現路由守衛

主要的設計思維是在router的流程中進行驗證,我們來看如何修正src\router\index.ts檔案:

index.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
router.beforeEach((to,from,next) =>{
const isLogin:boolean = localStorage.token ? true : false;

// console.log(`isLogin:${isLogin}`);
// console.log(to.path);

if(to.path ==='/')
{
next('/login');
}
else if(to.path === '/login' ){
next();
}
else {

isLogin ? next() : next("/login");
}
})

2. 完整程式碼

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import {createRouter,createWebHistory,RouteRecordRaw} from 'vue-router'

const routes: Array<RouteRecordRaw> =[
{
path:"/",
name:"Login",
component:() => import("../views/Login.vue")
},
{
path:"/login",
name:"Login",
component:() => import("../views/Login.vue")
},
{
path:"/main",
name:"Main",
component:() => import("../views/Main.vue")
},
{
path:"/:catchAll(.*)",
name:"404",
component:() => import("../views/404.vue")
}
]



const router = createRouter(
{
history: createWebHistory(),
routes
}
)

router.beforeEach((to,from,next) =>{
const isLogin:boolean = localStorage.token ? true : false;

// console.log(`isLogin:${isLogin}`);
// console.log(to.path);

if(to.path ==='/')
{
next('/login');
}
else if(to.path === '/login' ){
next();
}
else {

isLogin ? next() : next("/login");
}
})

export default router