实现登录

This commit is contained in:
2025-09-30 22:35:36 +08:00
parent effc2c06e0
commit a2a9cc1450
6 changed files with 198 additions and 23 deletions

View File

@@ -7,15 +7,17 @@ import App from './App.vue';
import Home from './components/Home.vue';
import DeviceList from './components/DeviceList.vue';
import PlanList from './components/PlanList.vue';
import LoginForm from './components/LoginForm.vue'; // 导入登录组件
// 导入全局样式
import './assets/styles/main.css';
// 配置路由
const routes = [
{ path: '/', component: Home },
{ path: '/devices', component: DeviceList },
{ path: '/plans', component: PlanList }
{ path: '/', component: Home, meta: { requiresAuth: true } },
{ path: '/devices', component: DeviceList, meta: { requiresAuth: true } },
{ path: '/plans', component: PlanList, meta: { requiresAuth: true } },
{ path: '/login', component: LoginForm }
];
const router = createRouter({
@@ -23,6 +25,21 @@ const router = createRouter({
routes
});
// 全局路由守卫
router.beforeEach((to, from, next) => {
const loggedIn = localStorage.getItem('jwt_token');
if (to.matched.some(record => record.meta.requiresAuth) && !loggedIn) {
// 如果路由需要认证但用户未登录,则重定向到登录页
next('/login');
} else if (to.path === '/login' && loggedIn) {
// 如果用户已登录但试图访问登录页,则重定向到首页
next('/');
} else {
next(); // 正常放行
}
});
// 创建Vue应用实例
const app = createApp(App);
@@ -32,9 +49,5 @@ app.use(ElementPlus);
// 使用路由
app.use(router);
// 初始化服务(示例)
// app.config.globalProperties.$api = ApiService;
// app.config.globalProperties.$utils = Utils;
// 挂载应用
app.mount('#app');
app.mount('#app');