vue2.0项目实战 --登录权限使用全局公用方法取值

项目开发实战时,遇到要通过鉴权接口获取用户信息和权限信息,这时,一般会用公共的方法或者公共的变量来存储获取这些信息,

常规的在用jquery作为框架开发,比较简单,一般是在登录页面的js文件中用ajax请求后台接口,返回的数据保存在Cookie或者localStorage中,如下:

login.js

$.ajax({
    url:timestamp(setIp+"/zqzwfwsys/Login/LoginIn"),
    type:"POST",            
    dataType:'json',
    contentType: 'application/json; charset=utf-8',
    data:JSON.stringify({
        "userName":$(".nameBox input").val(),
        "password":$(".pasBox input").val()
    }),
    success: function(data){
      console.log(data);
      if(data.code == '0'){
        setCookie("loginName",data.result.loginNam);
        setCookie("userName",data.result.userName);
      }
    }
})

common.js

var loginName = getCookie("loginName");
var userName = getCookie("userName");

这样loginName和userName就是全局变量可以在所有引入common.js的页面直接使用了。

接下来是Vue开发的项目实战,稍微复杂一点,直接上代码解析:

main.js--首先是要配置这个文件,这里引用了公共样式,路由等,我们只看最后一个‘登录user’,接下来就是要用到它

import Vue from 'vue';
import App from './App';
import router from './router';
import 'babel-polyfill';
import '@/assets/scss/color.scss';
import '@/assets/scss/common.scss';

//表单验证
import VeeValidate from './validator'
Vue.use(VeeValidate);

//api地址
import api from './assets/js/api';
Vue.prototype.$api = api;

//axios
import axios from './axios';
Vue.prototype.$axios = axios;

//登录user
import user from './assets/js/userinfo';
Vue.prototype.$user = user;

 

index.vue--login页面文件下的vue文件

this.$axios.get(Ip + '/userAuth/systemUserAuthentication',{
    params: {
        "sysUserCode": this.name,
        "systemInfoId": this.psd
    }
}).then((res) => {
    if (res.data.success || true) {
        let userObj = res.data.systemUser,
            userString = JSON.stringify(userObj);
        localStorage.setItem(userinfo.userStorage, userString);

      //保存用户信息
      localStorage.setItem(userinfo.userNameKey, this.name);
      localStorage.setItem(userinfo.userRememberKey, this.isRemember ? 1 : 0);

      if(this.isRemember) {   // 判断是否需要记住密码
        localStorage.setItem(userinfo.userIdKey, userObj.staffId);
        localStorage.setItem(userinfo.userPwKey, this.psd);
      } else {
        sessionStorage.setItem(userinfo.userIdKey, userObj.staffId);
        localStorage.removeItem(userinfo.userIdKey);
        localStorage.removeItem(userinfo.userPwKey);
      }

    } else {
        this.$message.warning({"message": "当前用户没有权限!"});
    }  
}).catch(err => {
    this.$message.warning({"message": "服务器异常!"})
})

 

userinfo.js -- 用来处理用户登录信息的文件,我就直接贴代码,不做删减了

export default {
    userNameKey:'USER_NAME',
    userPwKey:'USER_PW',
    userIdKey:'USER_ID',
    userTimeKey:'USER_LOGIN_TIME',
    userRememberKey:'USER_REMEMBER',
    userStorage: 'USER_STORAGE',
    getInfo : function (){
        let userName = localStorage.getItem(this.userNameKey);
        let userPw = localStorage.getItem(this.userPwKey);
        let userRemember = localStorage.getItem(this.userRememberKey);
        let userStorage = JSON.parse(localStorage.getItem(this.userStorage));

        let userId = '';
        if(userRemember == '1'){   // 判断是否要记住密码
            userId = localStorage.getItem(this.userIdKey);
        }else{
            userId = sessionStorage.getItem(this.userIdKey);    
        }
        let userLoginTime = localStorage.getItem(this.userTimeKey);

        return {
            name:userName,
            id:userId,
            loginTime:userLoginTime,
            userStorage: userStorage,
            depart:'市场部',
            departId:'10',
        }
    },
    isValidLogin: function(){
        let userInfo = this.getInfo();
        if(userInfo.id) return true;
    },
    redirect:function(){
        window.location.reload();
    },
    validLogin:function(){
        if(this.isValidLogin()){

        }else{
            this.redirect();
        }
    },
    exitLogin:function(){   // 退出删除localStorage
        let userRemember = localStorage.getItem(this.userRememberKey);
        if(userRemember == '1'){
            localStorage.removeItem(this.userIdKey);
        }else{
            sessionStorage.removeItem(this.userIdKey);
        }

        localStorage.removeItem(this.userRememberKey);
        localStorage.removeItem(this.userIdKey);
        localStorage.removeItem(this.userPwKey);
        localStorage.removeItem(this.userStorage);
        localStorage.removeItem(this.userNameKey);

        this.redirect();
    }
}

接下来其他文件要引用鉴权接口返回的信息

this.$user.getInfo().id
this.$user.getInfo().userStorage

这种写法适用项目大量适用了鉴权接口返回的用户信息,当然,写法仅供参考

 

posted @ 2018-12-03 15:30  望兰鸟  阅读(2160)  评论(0编辑  收藏  举报