element-admin源码解读
源码地址
⽤户登录页⾯
⽤户访问项⽬的根⽬录/时,要进⼊根⽬录“/”,这⾥要看路由⾥的配置,
router/index.js有⼀段代码
{
path:'/',
component: Layout,
redirect:'/dashboard',
children:[
{
path:'dashboard',
component:()=>import('@/views/dashboard/index'),
name:'Dashboard',
meta:{ title:'Dashboard', icon:'dashboard', affix:true}
}
]
}
这个组件Layout就是第⼀个要进⼊的页⾯。在进⼊这个页⾯时,路由会被下⾯的路由守卫拦截,下⾯是main.js⾥的代码:
import Vue from'vue'
import Cookies from'js-cookie'
import'normalize.css/normalize.css'// a modern alternative to CSS resets
import Element from'element-ui'
import'./styles/element-variables.scss'
import'@/styles/index.scss'// global css
import App from'./App'
import store from'./store'
import router from'./router'
import'./icons'// icon
import'./permission'// permission control
import'./utils/error-log'// error log
import*as filters from'./filters'// global filters
/**
* If you don't want to use mock-server
* you want to use MockJs for mock api
* you can execute: mockXHR()
*
* Currently MockJs will be used in the production environment,
* please remove it before going online ! ! !
*/
v.NODE_ENV==='production'){
const{ mockXHR }=require('../mock')
mockXHR()
}
Vue.use(Element,{
size: ('size')||'medium'// set element-ui default size
})
// register global utility filters
Object.keys(filters).forEach(key =>{
Vue.filter(key, filters[key])
})
new Vue({
el:'#app',
router,
store,
render: h =>h(App)
})
上⾯的代码⾥第17⾏引⼊了⼀个js⽂件
import'./permission'// permission control
这个⽂件⾥的源码中如下:
import router from'./router'
import store from'./store'
import{ Message }from'element-ui'
import NProgress from'nprogress'// progress bar
import'nprogress/nprogress.css'// progress bar style
import{ getToken }from'@/utils/auth'// get token from cookie
import getPageTitle from'@/utils/get-page-title'
const whiteList =['/login','/auth-redirect']// no redirect whitelist
router.beforeEach(async(to,from, next)=>{
// start progress bar
NProgress.start()
// set page title
document.title =a.title)
// determine whether the user has logged in
const hasToken =getToken()
vue element adminif(hasToken){
if(to.path ==='/login'){
// if is logged in, redirect to the home page
next({ path:'/'})
NProgress.done()
}else{
// determine whether the user has obtained his permission roles through getInfo
const hasRoles = les && les.length >0
if(hasRoles){
next()
}else{
try{
// get user info
// note: roles must be a object array! such as: ['admin'] or ,['developer','editor']
const{ roles }=await store.dispatch('user/getInfo')
// generate accessible routes map based on roles
const accessRoutes =await store.dispatch('permission/generateRoutes', roles)
// dynamically add accessible routes
router.addRoutes(accessRoutes)
// hack method to ensure that addRoutes is complete
// set the replace: true, so the navigation will not leave a history record
next({...to, replace:true})
}catch(error){
// remove token and go to login page to re-login
await store.dispatch('user/resetToken')
<(error ||'Has Error')
next(`/login?redirect=${to.path}`)
NProgress.done()
}
}
}
}else{
/
* has no token*/
if(whiteList.indexOf(to.path)!==-1){
// in the free login whitelist, go directly
next()
}else{
// other pages that do not have permission to access are redirected to the login page.
next(`/login?redirect=${to.path}`)
NProgress.done()
}
}
})
router.afterEach(()=>{
// finish progress bar
NProgress.done()
})
})
引⼊了路由守卫
router.beforeEach
const hasToken =getToken()
要从cookie⾥引⼊token
getToken()⽅法是从哪⾥来的呢?
第6⾏代码显⽰是从utils/auth⽂件⾥来的
import{ getToken }from'@/utils/auth'
auth的源码如下:
import Cookies from'js-cookie'
const TokenKey ='Admin-Token'
export function getToken(){
(TokenKey)
}
export function setToken(token){
return Cookies.set(TokenKey, token)
}
export function removeToken(){
ve(TokenKey)
}
可以看出,auth.js⾥引⼊了js-cookie这个包,js-cookie就是从cookie⾥get和set值
这⾥⽐较清楚了。
我们回到路由上,/src/permission.js的代码上
如果⽤户没有token,在代码的第52⾏
next(`/login?redirect=${to.path}`)
让⽤户跳转到login页⾯,还有⼀个redirect的参数,值是Layout路由配置中的 redirect: '/dashboard’⾥的值
在login.vue页⾯⾥⽤户点击登录,会进⼊login.vue
代码如下:
<script>
import{ validUsername }from'@/utils/validate'
import SocialSign from'./components/SocialSignin'
export default{
name:'Login',
components:{ SocialSign },
data(){
const validateUsername=(rule, value, callback)=>{
if(!validUsername(value)){
callback(new Error('Please enter the correct user name'))
}else{
callback()
}
}
const validatePassword=(rule, value, callback)=>{
if(value.length <6){
callback(new Error('The password can not be less than 6 digits'))
callback(new Error('The password can not be less than 6 digits'))
}else{
callback()
}
}
return{
loginForm:{
username:'admin',
password:'111111'
},
loginRules:{
username:[{ required:true, trigger:'blur', validator: validateUsername }], password:[{ required:true, trigger:'blur', validator: validatePassword }] },
passwordType:'password',
capsTooltip:false,
loading:false,
showDialog:false,
redirect: undefined,
otherQuery:{}
}
},
watch:{
$route:{
handler:function(route){
const query = route.query
if(query){
}
},
immediate:true
}
},
created(){
// window.addEventListener('storage', this.afterQRScan)
},
mounted(){
if(this.loginForm.username ===''){
this.$refs.username.focus()
}else if(this.loginForm.password ===''){
this.$refs.password.focus()
}
},
destroyed(){
// veEventListener('storage', this.afterQRScan)
},
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
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论