在 Vue 3.0 使用 Vue Router 制定認證路由

做法

修改 router/index.js 檔。

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
import { createRouter, createWebHashHistory } from 'vue-router';
import store from '@/store';

const routes = [
{
path: '/login',
name: 'login',
component: () => import(/* webpackChunkName: "login" */ '@/views/Login.vue'),
meta: {
requiresGuest: true,
},
},
{
path: '/',
name: 'home',
component: () => import(/* webpackChunkName: "home" */ '@/views/Home.vue'),
meta: {
requiresAuth: true,
},
},
{
path: '/:pathMatch(.*)*',
redirect: {
name: 'home',
},
},
];

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

router.beforeEach((to, from, next) => {
// 檢查該路由是否需要令牌
if (to.meta.requiresAuth) {
// 如果有令牌,就通行,否則導到登入頁
return store.state.token ? next() : next({ name: 'login' });
}
// 檢查該路由是否不可有令牌
if (to.meta.requiresGuest)) {
// 如果有令牌,就導到首頁
return store.state.token ? next({ name: 'home' }) : next();
}
return next();
});

export default router;

參考資料