清空默认

This commit is contained in:
jqtmviyu@gmail.com 2021-01-13 15:33:15 +08:00
parent 2bb23e5d0f
commit 2fb067308d
5 changed files with 235 additions and 219 deletions

View File

@ -1,24 +1,24 @@
import request from '@/utils/request' // import request from '@/utils/request'
export function login(data) { export function login(data) {
return request({ // return request({
url: '/vue-admin-template/user/login', // url: '/vue-admin-template/user/login',
method: 'post', // method: 'post',
data // data
}) // })
} }
export function getInfo(token) { export function getInfo(token) {
return request({ // return request({
url: '/vue-admin-template/user/info', // url: '/vue-admin-template/user/info',
method: 'get', // method: 'get',
params: { token } // params: { token }
}) // })
} }
export function logout() { export function logout() {
return request({ // return request({
url: '/vue-admin-template/user/logout', // url: '/vue-admin-template/user/logout',
method: 'post' // method: 'post'
}) // })
} }

View File

@ -1,64 +1,64 @@
import router from './router' // import router from './router'
import store from './store' // import store from './store'
import { Message } from 'element-ui' // import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar // import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style // import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie // import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title' // import getPageTitle from '@/utils/get-page-title'
NProgress.configure({ showSpinner: false }) // NProgress Configuration // NProgress.configure({ showSpinner: false }) // NProgress Configuration
const whiteList = ['/login'] // no redirect whitelist // const whiteList = ['/login'] // no redirect whitelist
router.beforeEach(async(to, from, next) => { // router.beforeEach(async(to, from, next) => {
// start progress bar // // start progress bar
NProgress.start() // NProgress.start()
// set page title // // set page title
document.title = getPageTitle(to.meta.title) // document.title = getPageTitle(to.meta.title)
// determine whether the user has logged in // // determine whether the user has logged in
const hasToken = getToken() // const hasToken = getToken()
if (hasToken) { // if (hasToken) {
if (to.path === '/login') { // if (to.path === '/login') {
// if is logged in, redirect to the home page // // if is logged in, redirect to the home page
next({ path: '/' }) // next({ path: '/' })
NProgress.done() // NProgress.done()
} else { // } else {
const hasGetUserInfo = store.getters.name // const hasGetUserInfo = store.getters.name
if (hasGetUserInfo) { // if (hasGetUserInfo) {
next() // next()
} else { // } else {
try { // try {
// get user info // // get user info
await store.dispatch('user/getInfo') // await store.dispatch('user/getInfo')
next() // next()
} catch (error) { // } catch (error) {
// remove token and go to login page to re-login // // remove token and go to login page to re-login
await store.dispatch('user/resetToken') // await store.dispatch('user/resetToken')
Message.error(error || 'Has Error') // Message.error(error || 'Has Error')
next(`/login?redirect=${to.path}`) // next(`/login?redirect=${to.path}`)
NProgress.done() // NProgress.done()
} // }
} // }
} // }
} else { // } else {
/* has no token*/ // /* has no token*/
if (whiteList.indexOf(to.path) !== -1) { // if (whiteList.indexOf(to.path) !== -1) {
// in the free login whitelist, go directly // // in the free login whitelist, go directly
next() // next()
} else { // } else {
// other pages that do not have permission to access are redirected to the login page. // // other pages that do not have permission to access are redirected to the login page.
next(`/login?redirect=${to.path}`) // next(`/login?redirect=${to.path}`)
NProgress.done() // NProgress.done()
} // }
} // }
}) // })
router.afterEach(() => { // router.afterEach(() => {
// finish progress bar // // finish progress bar
NProgress.done() // NProgress.done()
}) // })

View File

@ -1,8 +1,14 @@
// const getters = {
// sidebar: state => state.app.sidebar,
// device: state => state.app.device,
// token: state => state.user.token,
// avatar: state => state.user.avatar,
// name: state => state.user.name
// }
// export default getters
const getters = { const getters = {
sidebar: state => state.app.sidebar, sidebar: state => state.app.sidebar,
device: state => state.app.device, device: state => state.app.device
token: state => state.user.token,
avatar: state => state.user.avatar,
name: state => state.user.name
} }
export default getters export default getters

View File

@ -1,97 +1,103 @@
import { login, logout, getInfo } from '@/api/user' // import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth' // import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router' // import { resetRouter } from '@/router'
const getDefaultState = () => { // const getDefaultState = () => {
return { // return {
token: getToken(), // token: getToken(),
name: '', // name: '',
avatar: '' // avatar: ''
} // }
} // }
const state = getDefaultState() // const state = getDefaultState()
const mutations = { // const mutations = {
RESET_STATE: (state) => { // RESET_STATE: (state) => {
Object.assign(state, getDefaultState()) // Object.assign(state, getDefaultState())
}, // },
SET_TOKEN: (state, token) => { // SET_TOKEN: (state, token) => {
state.token = token // state.token = token
}, // },
SET_NAME: (state, name) => { // SET_NAME: (state, name) => {
state.name = name // state.name = name
}, // },
SET_AVATAR: (state, avatar) => { // SET_AVATAR: (state, avatar) => {
state.avatar = avatar // state.avatar = avatar
} // }
} // }
const actions = { // const actions = {
// user login // // user login
login({ commit }, userInfo) { // login({ commit }, userInfo) {
const { username, password } = userInfo // const { username, password } = userInfo
return new Promise((resolve, reject) => { // return new Promise((resolve, reject) => {
login({ username: username.trim(), password: password }).then(response => { // login({ username: username.trim(), password: password }).then(response => {
const { data } = response // const { data } = response
commit('SET_TOKEN', data.token) // commit('SET_TOKEN', data.token)
setToken(data.token) // setToken(data.token)
resolve() // resolve()
}).catch(error => { // }).catch(error => {
reject(error) // reject(error)
}) // })
}) // })
}, // },
// get user info // // get user info
getInfo({ commit, state }) { // getInfo({ commit, state }) {
return new Promise((resolve, reject) => { // return new Promise((resolve, reject) => {
getInfo(state.token).then(response => { // getInfo(state.token).then(response => {
const { data } = response // const { data } = response
if (!data) { // if (!data) {
return reject('Verification failed, please Login again.') // return reject('Verification failed, please Login again.')
} // }
const { name, avatar } = data // const { name, avatar } = data
commit('SET_NAME', name) // commit('SET_NAME', name)
commit('SET_AVATAR', avatar) // commit('SET_AVATAR', avatar)
resolve(data) // resolve(data)
}).catch(error => { // }).catch(error => {
reject(error) // reject(error)
}) // })
}) // })
}, // },
// user logout // // user logout
logout({ commit, state }) { // logout({ commit, state }) {
return new Promise((resolve, reject) => { // return new Promise((resolve, reject) => {
logout(state.token).then(() => { // logout(state.token).then(() => {
removeToken() // must remove token first // removeToken() // must remove token first
resetRouter() // resetRouter()
commit('RESET_STATE') // commit('RESET_STATE')
resolve() // resolve()
}).catch(error => { // }).catch(error => {
reject(error) // reject(error)
}) // })
}) // })
}, // },
// remove token // // remove token
resetToken({ commit }) { // resetToken({ commit }) {
return new Promise(resolve => { // return new Promise(resolve => {
removeToken() // must remove token first // removeToken() // must remove token first
commit('RESET_STATE') // commit('RESET_STATE')
resolve() // resolve()
}) // })
} // }
} // }
// export default {
// namespaced: true,
// state,
// mutations,
// actions
// }
export default { export default {
namespaced: true, namespaced: true,
state, state: {},
mutations, mutations: {},
actions actions: {}
} }

View File

@ -1,7 +1,7 @@
import axios from 'axios' import axios from 'axios'
import { MessageBox, Message } from 'element-ui' // import { MessageBox, Message } from 'element-ui'
import store from '@/store' // import store from '@/store'
import { getToken } from '@/utils/auth' // import { getToken } from '@/utils/auth'
// create an axios instance // create an axios instance
const service = axios.create({ const service = axios.create({
@ -15,71 +15,75 @@ service.interceptors.request.use(
config => { config => {
// do something before request is sent // do something before request is sent
if (store.getters.token) { // if (store.getters.token) {
// let each request carry token // // let each request carry token
// ['X-Token'] is a custom headers key // // ['X-Token'] is a custom headers key
// please modify it according to the actual situation // // please modify it according to the actual situation
config.headers['X-Token'] = getToken() // config.headers['X-Token'] = getToken()
} // }
return config return config
}, }//,
error => { // error => {
// do something with request error // // do something with request error
console.log(error) // for debug // console.log(error) // for debug
return Promise.reject(error) // return Promise.reject(error)
} // }
) )
// response interceptor // response interceptor
service.interceptors.response.use( // service.interceptors.response.use(
/** // /**
* If you want to get http information such as headers or status // * If you want to get http information such as headers or status
* Please return response => response // * Please return response => response
*/ // */
/** // /**
* Determine the request status by custom code // * Determine the request status by custom code
* Here is just an example // * Here is just an example
* You can also judge the status by HTTP Status Code // * You can also judge the status by HTTP Status Code
*/ // */
response => { // response => {
const res = response.data // const res = response.data
// if the custom code is not 20000, it is judged as an error. // // if the custom code is not 20000, it is judged as an error.
if (res.code !== 20000) { // if (res.code !== 20000) {
Message({ // Message({
message: res.message || 'Error', // message: res.message || 'Error',
type: 'error', // type: 'error',
duration: 5 * 1000 // duration: 5 * 1000
}) // })
// 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired; // // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
if (res.code === 50008 || res.code === 50012 || res.code === 50014) { // if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
// to re-login // // to re-login
MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', { // MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
confirmButtonText: 'Re-Login', // confirmButtonText: 'Re-Login',
cancelButtonText: 'Cancel', // cancelButtonText: 'Cancel',
type: 'warning' // type: 'warning'
}).then(() => { // }).then(() => {
store.dispatch('user/resetToken').then(() => { // store.dispatch('user/resetToken').then(() => {
location.reload() // location.reload()
}) // })
}) // })
} // }
return Promise.reject(new Error(res.message || 'Error')) // return Promise.reject(new Error(res.message || 'Error'))
} else { // } else {
return res // return res
} // }
}, // },
error => { // error => {
console.log('err' + error) // for debug // console.log('err' + error) // for debug
Message({ // Message({
message: error.message, // message: error.message,
type: 'error', // type: 'error',
duration: 5 * 1000 // duration: 5 * 1000
}) // })
return Promise.reject(error) // return Promise.reject(error)
} // }
) // )
service.interceptors.response.use(res => {
return res
})
export default service export default service