目录
1、前端登录
1.1改造前端登录页面和表单验证代码
<template>
<div class="login-container">
<el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form" autocomplete="on" label-position="left">
<div class="title-container">
<h3 class="title">通用权限管理系统</h3>
</div>
<el-form-item prop="username">
<span class="svg-container">
<svg-icon icon-class="user" />
</span>
<el-input
ref="username"
v-model="loginForm.username"
placeholder="请输入用户名"
name="username"
type="text"
tabindex="1"
autocomplete="on"
/>
</el-form-item>
<el-tooltip v-model="capsTooltip" content="Caps lock is On" placement="right" manual>
<el-form-item prop="password">
<span class="svg-container">
<svg-icon icon-class="password" />
</span>
<el-input
:key="passwordType"
ref="password"
v-model="loginForm.password"
:type="passwordType"
placeholder="请输入密码"
name="password"
tabindex="2"
autocomplete="on"
@keyup.native="checkCapslock"
@blur="capsTooltip = false"
@keyup.enter.native="handleLogin"
/>
<span class="show-pwd" @click="showPwd">
<svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
</span>
</el-form-item>
</el-tooltip>
<el-button :loading="loading" type="primary" style="width:100%;margin-bottom:30px;" @click.native.prevent="handleLogin">登录</el-button>
</el-form>
</div>
</template>
<script>
export default {
name: 'Login',
data() {
return {
loginForm: {
username: '',
password: ''
},
loginRules: {
username: [{ required: true, trigger: 'blur', message: "用户名不能为空" }],
password: [{ required: true, trigger: 'blur', message: "密码不能为空" }]
},
passwordType: 'password',
capsTooltip: false,
loading: false,
showDialog: false,
redirect: undefined,
otherQuery: {}
}
},
watch: {
$route: {
handler: function(route) {
const query = route.query
if (query) {
this.redirect = query.redirect
this.otherQuery = this.getOtherQuery(query)
}
},
immediate: true
}
},
mounted() {
if (this.loginForm.username === '') {
this.$refs.username.focus()
} else if (this.loginForm.password === '') {
this.$refs.password.focus()
}
},
methods: {
checkCapslock(e) {
const { key } = e
this.capsTooltip = key && key.length === 1 && (key >= 'A' && key <= 'Z')
},
showPwd() {
if (this.passwordType === 'password') {
this.passwordType = ''
} else {
this.passwordType = 'password'
}
this.$nextTick(() => {
this.$refs.password.focus()
})
},
handleLogin() {
this.$refs.loginForm.validate(valid => {
if (valid) {
this.loading = true
this.$store.dispatch('user/login', this.loginForm)
.then(() => {
this.$router.push({ path: this.redirect || '/', query: this.otherQuery })
this.loading = false
})
.catch(() => {
this.loading = false
})
} else {
console.log('error submit!!')
return false
}
})
},
getOtherQuery(query) {
return Object.keys(query).reduce((acc, cur) => {
if (cur !== 'redirect') {
acc[cur] = query[cur]
}
return acc
}, {})
}
// afterQRScan() {
// if (e.key === 'x-admin-oauth-code') {
// const code = getQueryObject(e.newValue)
// const codeMap = {
// wechat: 'code',
// tencent: 'code'
// }
// const type = codeMap[this.auth_type]
// const codeName = code[type]
// if (codeName) {
// this.$store.dispatch('LoginByThirdparty', codeName).then(() => {
// this.$router.push({ path: this.redirect || '/' })
// })
// } else {
// alert('第三方登录失败')
// }
// }
// }
}
}
</script>
<style lang="scss">
/* 修复input 背景不协调 和光标变色 */
/* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */
$bg:#283443;
$light_gray:#fff;
$cursor: #fff;
@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
.login-container .el-input input {
color: $cursor;
}
}
/* reset element-ui css */
.login-container {
.el-input {
display: inline-block;
height: 47px;
width: 85%;
input {
background: transparent;
border: 0px;
-webkit-appearance: none;
border-radius: 0px;
padding: 12px 5px 12px 15px;
color: $light_gray;
height: 47px;
caret-color: $cursor;
&:-webkit-autofill {
box-shadow: 0 0 0px 1000px $bg inset !important;
-webkit-text-fill-color: $cursor !important;
}
}
}
.el-form-item {
border: 1px solid rgba(255, 255, 255, 0.1);
background: rgba(0, 0, 0, 0.1);
border-radius: 5px;
color: #454545;
}
}
</style>
<style lang="scss" scoped>
$bg:#2d3a4b;
$dark_gray:#889aa4;
$light_gray:#eee;
.login-container {
min-height: 100%;
width: 100%;
background-color: $bg;
overflow: hidden;
.login-form {
position: relative;
width: 520px;
max-width: 100%;
padding: 160px 35px 0;
margin: 0 auto;
overflow: hidden;
}
.tips {
font-size: 14px;
color: #fff;
margin-bottom: 10px;
span {
&:first-of-type {
margin-right: 16px;
}
}
}
.svg-container {
padding: 6px 5px 6px 15px;
color: $dark_gray;
vertical-align: middle;
width: 30px;
display: inline-block;
}
.title-container {
position: relative;
.title {
font-size: 26px;
color: $light_gray;
margin: 0px auto 40px auto;
text-align: center;
font-weight: bold;
}
}
.show-pwd {
position: absolute;
right: 10px;
top: 7px;
font-size: 16px;
color: $dark_gray;
cursor: pointer;
user-select: none;
}
.thirdparty-button {
position: absolute;
right: 0;
bottom: 6px;
}
@media only screen and (max-width: 470px) {
.thirdparty-button {
display: none;
}
}
}
</style>
1.2 前后端接口联系调
(1)修改vue.config.js 文件中mock请求注释掉,并设置代理
devServer: {
port: port,
open: true,
overlay: {
warnings: false,
errors: true
},
// before: require('./mock/mock-server.js')
},
//代理配置
proxy:{
[process.env.VUE_APP_BASE_API]:{
target:"http://localhost:8089/api",
changeOrigin: true,
pathRewrite:{
'^/api':''
}
}
},
(2)修改main.js
(3)修改src/utils目录下的request.js脚本文件
import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
import qs from 'qs'
// create an axios instance
const service = axios.create({
baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
// withCredentials: true, // send cookies when cross-domain requests
timeout: 5000 // request timeout
})
// request interceptor
service.interceptors.request.use(
config => {
// do something before request is sent
if (store.getters.token) {
// let each request carry token
// ['X-Token'] is a custom headers key
// please modify it according to the actual situation
config.headers['token'] = getToken()
}
return config
},
error => {
// do something with request error
console.log(error) // for debug
return Promise.reject(error)
}
)
// response interceptor
service.interceptors.response.use(
response => {
const res = response.data
if (res.code !== 200) {
Message({
message: res.message || 'Error',
type: 'error',
duration: 5 * 1000
})
// 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
// to re-login
MessageBox.confirm('用户登录信息过期,请重新登录', '系统提示', {
confirmButtonText: '登录',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
store.dispatch('user/resetToken').then(() => {
location.reload()
})
})
}
return Promise.reject(new Error(res.message || 'Error'))
} else {
return res
}
},
error => {
console.log('err' + error) // for debug
Message({
message: error.message,
type: 'error',
duration: 5 * 1000
})
return Promise.reject(error)
}
)
//请求方法
const http ={
post(url,params){
return service.post(url,params,{
transformRequest: [(params)=>{
return JSON.stringify(params)
}],
headers:{
'Content-Type':'application/json'
}
})
},
put(url,params){
return service.put(url,params,{
transformRequest: [(params)=>{
return JSON.stringify(params)
}],
headers:{
'Content-Type':'application/json'
}
})
},
get(url,params){
return service.get(url,{
params:params,
paramsSerializer: (params)=>{
return qs.stringify(params)
}
})
},
get(url,params){
return service.get(url,{
params:params,
paramsSerializer: (params)=>{
return qs.stringify(params)
}
})
},
getRestApi(url,params){
let _params
if(Object.is(params,undefined||null)){
_params=''
}else{
_params='/'
for(const key in params){
console.log(key)
console.log(params[key])
if(params.hasOwnProperty(key)&¶ms[key]!==null &¶ms[key]!==''){
_params+=`${params[key]}/`
}
}
_params =params.substr(0,_params.length-1)
}
if (_params) {
return service.get(`${url}${_params}`)
}else{
return service.get(url)
}
},
delete(url,params){
let _params
if(Object.is(params,undefined||null)){
_params=''
}else{
_params='/'
for(const key in params){
if(params.hasOwnProperty(key)&¶ms[key]!==null &¶ms[key]!==''){
_params+=`${params[key]}/`
}
}
_params =params.substr(0,_params.length-1)
}
if (_params) {
return service.delete(url).catch(err=>{
message.error(err.msg)
return Promise.reject(err)
})
}
},
upload(url,params){
return service.post(url,params,{
headers:{
'Content-Type':'multipart/form-data'
}
})
},
login (url,params){
return service.post(url,params,{
transformRequest:[(params)=>{
return qs.stringify(params)
}],
headers:{
'Content-Type':'application/x-www-form-urlencoded'
}
})
},
}
export default http
(4)修改api/user.js 文件代码
import http from '@/utils/request'
export async function login(data) {
return await http.login("/api/user/login",data)
}
export async function getInfo() {
return await http.get("/api/sysUser/getInfo")
}
export async function logout(params) {
return await http.get("/api/sysUser/loginOut",params)
}
(5)修改env.development/env.production
VUE_APP_BASE_API = 'http://localhost:9999'
(6) 修改store/user.js
2、用户退出登录接口
2.1 退出登录接口
@PostMapping("/loginOut")
public Result logout(HttpServletRequest request, HttpServletResponse response) {
//获取token
String token = request.getParameter("token");
//如果没有从头部获取token,那么从参数里面获取
if (ObjectUtils.isEmpty(token)) {
token = request.getHeader("token");
}
//获取用户相关信息
Authentication authentication =
SecurityContextHolder.getContext().getAuthentication();
if (authentication != null) {
//清空用户信息
new SecurityContextLogoutHandler().logout(request, response,
authentication);
//清空redis里面的token
String key = "token_" + token;
redisService.del(key);
}
return Result.ok().message("用户退出成功");
}
2.2 前后端联调
(1)api/user.js 编写退出接口代码
(2)在utils/auth.js中添加清楚缓存方法
export function clearStorage(){
return sessionStorage.clear()
}
(3)layout/components/Navbar.vue组件,进行如下修改
3、封装信息确认提示框
3.1 信息确认提示框代码
在util/myconfirm.js文件,代码如下
3.2 挂载信息确认提示框
在main.js中将myconfirm挂载到vue 上
修改loginout代码
async logout() {
//确认提示
let confirm = await this.$myconfirm("确定要退出系统吗?")
//是否确认
if (confirm) {
let params = {token:getToken()}
let res = await logout(params)
if (res.success) {
removeToken()
clearStorage()
window.location.href ="/login"
}
}
}