Login.vue
<template>
<div class="login-container">
<el-card class="login-card">
<h3 class="login-title">用户登录</h3>
<el-form ref="loginForm" :model="user" :rules="rules" label-width="80px" class="login-form">
<el-form-item prop="username" label="用户名">
<el-input v-model="user.username" placeholder="请输入用户名"></el-input>
</el-form-item>
<el-form-item prop="password" label="密码">
<el-input v-model="user.password" type="password" placeholder="请输入密码"></el-input>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="userLogin">登录</el-button>
</el-form-item>
</el-form>
</el-card>
</div>
</template>
import { ref } from 'vue';
import {login} from "@/util/request";
import {filterMenus, initRouter} from "@/util/routeUtil";
import router from "@/router";
export default {
name:'Login',
setup() {
const user = ref({
username: 'admin',
password: '123456',
});
const rules = {
username: [
{ required: true, message: '请输入用户名', trigger: 'blur' },
],
password: [
{ required: true, message: '请输入密码', trigger: 'blur' },
],
};
function userLogin(){
console.log('user',user.value);
login(user.value).then(res => {
if (res.data.message='登录成功'){
//1、初始化路由
initRouter(res.data.data.role.menus)
window.localStorage.setItem('navMenus',JSON.stringify(filterMenus(res.data.data.role.menus)))
//2、跳转到主页
router.replace('/index')
}
})
}
return {
user,
rules,
userLogin,
};
},
};
<style>
.login-container {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
.login-card {
width: 400px;
padding: 20px;
}
.login-title {
text-align: center;
margin-bottom: 20px;
}
.login-form {
margin-top: 20px;
}
</style>
==注意:==原因:页面刷新后,页面会重新实例化路由数据,因为是动态路由,所以页面刷新后会将router置为router/index.js配置的原始路由数据,所以匹配路由地址的时候会报错。因为只需要在用户会话期间保持动态路由状态,而不需要在不同组件之间共享或进行状态管理,所以将其存储在localStorage中
##修改Login.vue,将后台传回的menus数据缓存到localStorage中
//1、初始化路由
initRouter(res.data.data.role.menus)
localStorage.setItem('navMenus',JSON.stringify(filterMenus(res.data.data.role.menus)))
localStorage.setItem('menus',JSON.stringify(res.data.data.role.menus))
localStorage.setItem('token',JSON.stringify(res.data.data.token))
修改main.js,页面刷新的时候,会出发main.js的调用,因此我们在页面刷新的时候,重新进行路由的初始化
import { createApp } from 'vue'
import App from './App.vue'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import 'element-plus/theme-chalk/dark/css-vars.css' //暗黑模式
import router from './router/index'
import {initRouter} from "@/util/routeUtil";
const app = createApp(App)
##初始化路由
const init = async ()=>{
if (localStorage.getItem('token')){
if (localStorage.getItem('menus')){
await initRouter(JSON.parse(localStorage.getItem('menus')))
}
}
}
##通过await,在挂在之前先进行路由的初始化
const call = async ()=>{
await init()
app.use(ElementPlus)
app.use(router)
app.mount('#app')
}
##调用
call()
欢迎转载,转载请标注出处。关注公众号: JAVA大师, 后台回复 资源,既可获取资源链接 !!!