vue-element-admin 学习

vue-element-admin 学习

相关地址:文档地址 | github 地址

1. 访问首页

访问 / 后,首先会到路由守卫,它会判断你有没有 token,没有的话看你是否在白名单中,如果不在,跳到登录页,并且会记录你的 to 的地址,如下:next(`/login?redirect=${to.path}`)。拼接到登录的路由上。

2. 登录页面

输入用户名和密码后,首先前端校验是否合法,然后通过 this.$store.dispatch('user/login', this.loginForm)动作去登录。

此处有 vuex 相关的内容,commit 类似于 git 做一个记录,然后解构 userInfo,获取用户名密码,return 一个 promise 对象,然后函数里调用了 login ,此时才真正发起了请求,请求接口如下。
获取到响应后应该会先经过响应拦截器,如果接口正常返回的话,此时会接受到 token ,然后解构响应 const { data } = response,设置 token,commit('SET_TOKEN', data.token) setToken(data.token)
此处 commit 是在当前内存中设置 token,保存当前状态,而 setToken 是在浏览器中设置 token。最后 resove()
在 login 页面按钮上,最后进行跳转。this.$router.push({ path: this.redirect || '/', query: this.otherQuery })。跳转到对应页面。

值得一提的这个 watch ,保存 redirect 的内容,使得跳转后可以到达原先想要到达的页面。

相关代码


src/permission.js

router.beforeEach(async(to, from, next) => {
  // start progress bar
  NProgress.start()

  // set page title
  document.title = getPageTitle(to.meta.title)

  // determine whether the user has logged in
  const hasToken = getToken()

  if (hasToken) {
    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      next({ path: '/' })
      NProgress.done() // hack: https://github.com/PanJiaChen/vue-element-admin/pull/2939
    } else {
      // determine whether the user has obtained his permission roles through getInfo
      const hasRoles = store.getters.roles && store.getters.roles.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')
          Message.error(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()
    }
  }
})

src/views/login/index.vue

  watch: {
    $route: {
      handler: function(route) {
        const query = route.query
        if (query) {
          this.redirect = query.redirect
          this.otherQuery = this.getOtherQuery(query)
        }
      },
      immediate: true
    }
  },
export function login(data) {
  return request({
    url: '/vue-element-admin/user/login',
    method: 'post',
    data
  })
}

setToken src/utils/auth.js

import Cookies from 'js-cookie'

export function setToken(token) {
  return Cookies.set(TokenKey, token)
}

src/store/modules/user.js

const state = {
  token: getToken(),
  name: '',
  avatar: '',
  introduction: '',
  roles: []
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password }).then(response => {
        const { data } = response
        commit('SET_TOKEN', data.token)
        setToken(data.token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

login 请求 src/api/user.js

export function login(data) {
  return request({
    url: '/vue-element-admin/user/login',
    method: 'post',
    data
  })
}

src/views/login/index.vue

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
        }
      })
    },
posted @ 2022-07-22 23:46  绣幕  阅读(143)  评论(0编辑  收藏  举报