前端增加登录路由卫士

main
yuan 2 weeks ago
parent 78c5bffcce
commit d8cf875a85

@ -70,4 +70,5 @@ public class ResourcesConfig implements WebMvcConfigurer
// 返回新的CorsFilter
return new CorsFilter(source);
}
}

@ -9,10 +9,11 @@
"version": "0.1.0",
"dependencies": {
"axios": "^1.7.7",
"core-js": "^3.8.3",
"core-js": "^3.39.0",
"element-ui": "^2.15.14",
"vue": "^2.6.14",
"vue-router": "^3.5.1"
"vue-router": "^3.5.1",
"vuex": "^3.6.2"
},
"devDependencies": {
"@vue/cli-plugin-babel": "~5.0.0",
@ -9444,6 +9445,14 @@
"prettier": "^1.18.2 || ^2.0.0"
}
},
"node_modules/vuex": {
"version": "3.6.2",
"resolved": "https://registry.npmmirror.com/vuex/-/vuex-3.6.2.tgz",
"integrity": "sha512-ETW44IqCgBpVomy520DT5jf8n0zoCac+sxWnn+hMe/CzaSejb/eVw2YToiXYX+Ex/AuHHia28vWTq4goAexFbw==",
"peerDependencies": {
"vue": "^2.0.0"
}
},
"node_modules/watchpack": {
"version": "2.4.2",
"resolved": "https://registry.npmmirror.com/watchpack/-/watchpack-2.4.2.tgz",

@ -8,10 +8,11 @@
},
"dependencies": {
"axios": "^1.7.7",
"core-js": "^3.8.3",
"core-js": "^3.39.0",
"element-ui": "^2.15.14",
"vue": "^2.6.14",
"vue-router": "^3.5.1"
"vue-router": "^3.5.1",
"vuex": "^3.6.2"
},
"devDependencies": {
"@vue/cli-plugin-babel": "~5.0.0",

@ -27,6 +27,7 @@
<script>
import axios from 'axios';
import {mapActions} from "vuex";
export default {
data() {
@ -60,31 +61,39 @@ export default {
const response = await axios.post('http://localhost:8080/login', {
username: this.username,
password: this.password,
code: this.code,//
uuid: this.uuid
code: this.code, //
uuid: this.uuid,
}, {
headers: {
'Content-Type': 'application/json' // JSON
'Content-Type': 'application/json', //
}
});
console.log('用户名',this.username);
console.log('密码',this.password);
console.log('验证码',this.code);
console.log('uuid',this.uuid);
if (response.data.code === 200) {
console.log('登录成功', response.data);
window.location.href = 'http://localhost:8081'; //
// token response.data.token
const token = response.data.token;
// token Vuex localStorage
this.setToken(token); // 使 Vuex action token
// //
// this.$router.push('/HomeView');
//
window.location.href = 'http://localhost:8081';
} else {
console.error('登录失败', response.data.msg);
this.refreshCaptcha(); //
}
} catch (error) {
console.error('登录失败', error);
//
this.refreshCaptcha();
this.refreshCaptcha(); //
}
},
// Vuex action
...mapActions(['setToken']),
//
refreshCaptcha() {
this.fetchCaptcha();

@ -1,18 +1,24 @@
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import Vue from 'vue';
import App from './App.vue';
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import './assets/gloable.css'
import './assets/gloable.css';
import store from './store'; // 确保这个路径是正确的
import router from './router';
import request from "@/utils/request";
Vue.config.productionTip = false
// 使用 ElementUI 组件库
Vue.use(ElementUI, { size: 'small' });
Vue.prototype.request=request
// 将 request 注册为 Vue 的实例属性
Vue.prototype.request = request;
// 关闭生产提示
Vue.config.productionTip = false;
// 创建 Vue 实例
new Vue({
store, // 确保 Vuex store 被正确注册
router,
render: h => h(App)
}).$mount('#app')
render: h => h(App),
}).$mount('#app');

@ -3,6 +3,7 @@ import VueRouter from 'vue-router';
import HomeView from '../views/HomeView.vue';
import Login from '../components/Login.vue';
import Register from '../components/Register.vue';
import store from '../store'; // 引入 Vuex store
Vue.use(VueRouter);
@ -10,7 +11,8 @@ const routes = [
{
path: '/',
name: 'home',
component: HomeView
component: HomeView,
meta: { requiresAuth: true } // 标记该页面需要登录
},
{
path: '/login',
@ -33,4 +35,19 @@ const router = new VueRouter({
routes
});
// 路由守卫
router.beforeEach((to, from, next) => {
// 判断该路由是否需要登录权限
if (to.matched.some(record => record.meta.requiresAuth)) {
// 如果未登录,跳转到登录页
if (!store.state.token) { // 使用 Vuex 中的 token 判断登录状态
next({ name: 'Login' });
} else {
next(); // 放行
}
} else {
next(); // 不需要登录,直接访问
}
});
export default router;

@ -0,0 +1,28 @@
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
export default new Vuex.Store({
state: {
token: localStorage.getItem('Authorization') || '', // 初始化 token
},
mutations: {
setToken(state, token) {
state.token = token;
localStorage.setItem('Authorization', token);
},
clearToken(state) {
state.token = '';
localStorage.removeItem('Authorization');
},
},
actions: {
setToken({ commit }, token) {
commit('setToken', token);
},
clearToken({ commit }) {
commit('clearToken');
},
},
});

@ -91,12 +91,27 @@
<el-button class="ml-5" type="primary">搜索</el-button>
</div>
<div style="margin:10px 0">
<el-button type="primary">新增<i class="el-icon-circle-plus-outline"></i></el-button>
<el-button type="danger">批量删除<i class="el-icon-circle-plus-outline"></i></el-button>
<el-button type="primary">导入<i class="el-icon-circle-plus-outline"></i></el-button>
<el-button type="primary">导出<i class="el-icon-circle-plus-outline"></i></el-button>
</div>
<el-table :data="tableData" border stripe header-row-class-name="headerBg">
<el-table-column prop="date" label="日期" width="140">
<el-table-column prop="sumclass" label="班级总数" width="140">
</el-table-column>
<el-table-column prop="sunnumclass" label="班级人数总数" width="120">
</el-table-column>
<el-table-column prop="name" label="姓名" width="120">
<el-table-column prop="exampapersum" label="试卷总数">
</el-table-column>
<el-table-column prop="address" label="地址">
<el-table-column prop="sumtimu" label="题目总数">
</el-table-column>
<el-table-column>
<template slot-scope="scope">
<el-button type="success">编辑 <i class="el-icon-edit"></i></el-button>
<el-button type="danger">删除 <i class="el-icon-circle-plus-outline"></i></el-button>
</template>
</el-table-column>
</el-table>
<div>
@ -104,7 +119,7 @@
:page-sizes="[5, 10, 15, 20]"
:page-size="10"
layout="total, sizes, prev, pager, next, jumper"
:total="400">
:total="total">
</el-pagination>
</div>
</el-main>
@ -117,20 +132,53 @@
export default {
name: 'HomeView',
data(){
const item = {
date: '2016-05-02',
name: '王小虎',
address: '上海市普陀区金沙江路 1518 弄'
};
return {
tableData: Array(10).fill(item),
tableData: [],
total:0,
collapseBtnClass:'el-icon-s-fold',
isCollapse: false,
sideWidth: 200,
logoTextShow: true
}
},
created() {
// 使 Vuex getter token
const token = this.$store.state.token;
console.log("token:",token);
if (!token) {
console.error('No token found, redirecting to login page...');
this.$router.push({ name: 'login' }); //
return;
}
this.fetchHomePageData(token);
},
methods: {
async fetchHomePageData(token) {
try {
const response = await fetch('http://localhost:8080/teacher/homepage/homepagesuju', {
method: 'GET',
headers: {
'Authorization': token,
'Content-Type': 'application/json',
}
});
const data = await response.json();
if (response.ok && data.code === 200) {
const { sumclass, sunnumclass, exampapersum, sumtimu } = data.data;
console.log("API Response:", data.data);
this.tableData = [
{ sumclass, sunnumclass, exampapersum, sumtimu }
];
} else {
console.error('Failed to fetch data:', data.msg || 'Unknown error');
}
} catch (error) {
console.error('Error fetching data:', error);
}
},
collapse(){
//
this.isCollapse = !this.isCollapse
@ -146,11 +194,6 @@ export default {
}
}
}
</script>
<!--<style>-->
<!--.headerBg{-->
<!-- background-color: #cccccc;-->
<!--}-->
<!--</style>-->

Loading…
Cancel
Save