天天看點

【Abp VNext】實戰入門(五):【5】前端管理界面 vue-element-admin —— 登入擷取 Access_Token 優化

前言:

vue-element-admin 自帶登入模式中真的有點兒惡心人,為什麼惡心人呢,分析一下:

1、接口方式采用axios封裝調用沒問題:utils/request.js;

2、資料緩存采用vuex插件存儲也沒有問題:store/moudles/user.js;

惡心就惡心在 它把調用登入接口相關的功能寫到了 緩存類user.js中,然後在裡面各種Mutations 和 Actions 調用 簡單的登入邏輯變得異常複雜化,如下為緩存類中的方法:

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
  }
}
           
getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const { data } = response
        if (!data) {
          reject('Verification failed, please Login again.')
        }
        const { roles, name, avatar, introduction } = data
        // roles must be a non-empty array
        if (!roles || roles.length <= 0) {
          reject('getInfo: roles must be a non-null array!')
        }
        commit('SET_ROLES', roles)
        commit('SET_NAME', name)
        commit('SET_AVATAR', avatar)
        commit('SET_INTRODUCTION', introduction)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  }
           

個人了解緩存類就是單純的緩存資料使用,不做任何業務邏輯功能方面的封裝,是以把登入相關的方法及業務剝離出去;

改造思路:

1、根目錄api目錄中存放接口申明:user.js device.js …

//api/user.js
import request from '@/http/request'
export function Login(data) {
  return request({
    url: '/connect/token',
    method: 'post',
    data: data
    //method: 'get',// 如果是get方法 下面要用 params 接收參數
    //params:data   // 
  })
}
           

2、根目錄新增business目錄存放一些業務功能封裝:user.js device.js

//business/user.js
import Api from '@/api/index'
import Store from '@/store/index'
import { asyncRoutes, constantRoutes } from '@/router'
import router from '@/router'
// 使用者登入方法
export const Login = (Input) => {
  // 2個Return配合  外部可采用 $common.BS_User.Login(input).then(res=>{console.log(res)});
  return Api.User.Login(Input).then(Res => {
    // 1、儲存token資訊 到/store/token.js 中
    SaveTokenInfo(Res)
    // 2、加載并儲存使用者基礎資訊:暫時存放 預設資訊 後續可二次調用
    LoadAndSaveUserBaseInfo(Res)
    return Res// 傳回原始資料 可供外部使用
  })
}
           

3、前端頁面調用:

//login/index.vue
const qs = require('qs')// 用于将Json格式資料參數 轉x-www-form-urlencoded格式所需參數
//登入參數
	loginForm: {
        username: 'admin',
        password: 'Admin12345*',//初始化預設密碼是:1q2w3E*
        client_id: 'GasMonitoring_App',
        client_secret: '1q2w3e*',
        grant_type: 'password'
      }

   //登入方法
   Login() { 
    let tmpInput=qs.stringify(this.loginForm);
	this.$Bussiness.User.Login(tmpInput).then((res) => {
          console.log(res)
        }) 
    }
           

總結:

這樣各司其職 有條不紊 再多都不會亂;

繼續閱讀