根据vuex全局状态管理+es6本地存储实现登录缓存以及token状态拦截
vuex--
import Vue from 'vue'
import Vuex from 'vuex'Vue.use(Vuex)
const store = new Vuex.Store({
state: {
hasLogin: false,
token: false,
userInfo: {},
},
mutations: {//登录
login(state, provider) {
state.hasLogin = true;
state.userInfo = provider.user;
state.token = provider.token;
uni.setStorage({//缓存用户登陆状态
key: 'userInfo',
data: provider
})
},//注销
logout(state) {
state.hasLogin = false;
state.token = false;
state.userInfo = {};
uni.removeStorage({
key: 'userInfo'
})
}
},
actions: {
}
})export default store
login.vue--验证码登录和账号密码登录,请求接口函数是 根据uni-app的request封装好的
async toLogin(){
if (this.islogin) {
// 验证码登录
if (!this.isPhone()) {
this.$api.msg("手机号码错误");
return;
}
let data = {
phone:this.phone,
code:this.checknum,
verificationCode_key:this.key,
type:2
}
uni.showLoading({ title: '登录中...', mask: true });
// 请求登录
let [err,res] = await this.$http.post('/user/login',data);
// 登录失败
if (!this.$http.errorCheck(err,res)){
uni.hideLoading();
return false;
}
// 登录成功 保存状态
if (res.data.code == 200000) {
// 调用vuex方法
this.login(res.data.data);
uni.hideLoading();
this.$api.msg(res.data.message);
// 返回上一步
setTimeout(()=>{
uni.navigateBack({ delta: 1 });
},300)
}else{
uni.hideLoading();
this.$api.msg(res.data.message);
}
}else{
if (!this.isPhone1()) {
this.$api.msg("手机号码错误");
return;
}
let Md5newPwd = md5('Shou'+this.password+'MAI__');
let data1 = {
phone:this.username,
password:Md5newPwd,
type:1
}
// 账号密码登录
uni.showLoading({ title: '登录中...', mask: true });
// 请求登录
let [err,res] = await this.$http.post('/user/login',data1);
// 登录失败
if (!this.$http.errorCheck(err,res)){
uni.hideLoading();
return false;
}
// 登录成功 保存状态
if (res.data.code == 200000) {
// 调用vuex方法
this.login(res.data.data);
uni.hideLoading();
this.$api.msg(res.data.message);
// 返回上一步
setTimeout(()=>{
uni.navigateBack({ delta: 1 });
},300)
}else{
uni.hideLoading();
this.$api.msg(res.data.message);
}
}
}
然后在app.vue里 uni-app的onLaunch 生命周期 判断缓存中是否有vuex存储的登录信息,如果存在,调用this.login()
onLaunch: function() {
// 用户状态保存--共享状态和用户信息
//获得保存在本地的用户信息
uni.getStorage({
key: 'userInfo',
success:(res) => {
console.log(res.data)
this.login(res.data);
}
});
},