在單頁面應用(SPA)框架中,如Vue.js,路由守衛是一種非常有用的功能,它允許你控制訪問路由的權限。Vue.js 使用 Vue Router 作為其官方路由管理器。路由守衛主要分為全局守衛和組件內守衛。
以下是如何設置路由守衛以允許某些路由公開訪問的示例:
- 全局前置守衛:在Vue Router的配置中,你可以使用
beforeEach
方法設置一個全局前置守衛,來檢查用戶是否登錄,并根據登錄狀態重定向用戶。
// router/index.js
import Vue from 'vue';
import Router from 'vue-router';
import Home from '../components/Home.vue';
import Dashboard from '../components/Dashboard.vue';Vue.use(Router);const router = new Router({routes: [{path: '/',name: 'Home',component: Home},{path: '/dashboard',name: 'Dashboard',component: Dashboard,meta: {requiresAuth: true // 標記需要認證的路由}}// 其他路由...]
});// 全局前置守衛
router.beforeEach((to, from, next) => {// 檢查路由是否需要認證if (to.matched.some(record => record.meta.requiresAuth)) {// 檢查用戶是否已登錄const isLoggedIn = // 你的登錄狀態檢查邏輯if (!isLoggedIn) {// 如果未登錄,則重定向到登錄頁面next({path: '/login',query: { redirect: to.fullPath } // 將原始目標路由作為參數傳遞});} else {next(); // 已登錄,繼續訪問目標路由}} else {next(); // 不需要認證,繼續訪問目標路由}
});export default router;
- 組件內守衛:你可以在路由組件內部使用
beforeRouteEnter
或beforeRouteEnter
守衛來實現類似的邏輯。
// components/Dashboard.vue
export default {data() {return {// 組件數據};},beforeRouteEnter(to, from, next) {// 檢查用戶登錄狀態const isLoggedIn = // 你的登錄狀態檢查邏輯if (!isLoggedIn) {// 如果未登錄,重定向到登錄頁面next('/login');} else {next();}},// 其他組件選項...
};
請注意,你需要替換登錄狀態檢查邏輯和路由組件的導入路徑以適應你的應用程序。此外,確保你的登錄狀態邏輯是安全的,并且不會暴露敏感信息。