uniapp全局靜默登錄
app.vue
$toast 是全局提示
getLogin() {
console.log(this, '開始登錄', this.$scope);
this.$toast.showLoading();
let accountInfo = wx.getAccountInfoSync();
console.log('小程序信息', accountInfo);
uni.login({
// #ifdef MP-ALIPAY
scopes: ['auth_base'], // 主動(dòng)
// scopes: ["auth_user"], // 主動(dòng)
// #endif
success: (res) => {
console.log('默認(rèn)登錄', res);
if (res.code) {
api
.login({ code: res.code, vsnNum: accountInfo.miniProgram.version })
.then((res) => {
uni.hideLoading();
if (!res.success) {
this.$toast.showToast(res.msg);
return;
}
console.log('登錄成功', res);
this.globalData.userInfo = res.data;
this.globalData.token = res.data.token;
uni.setStorageSync('token', res.data.token);
// 由于這里是網(wǎng)絡(luò)請(qǐng)求,可能會(huì)在 Page.onLoad 之后才返回 所以此處加入 callback 以防止這種情況
console.log('app this', this);
if (this.$scope.testDataCallback) {
console.log('有回調(diào)', this);
this.$scope.testDataCallback(res.data);
}
})
.catch((err) => {
console.log('小程序登錄失敗', err);
// #ifdef MP-WEIXIN
log.error('小程序登錄失敗', err);
// #endif
});
} else {
console.log('獲取用戶登錄態(tài)失敗!' + res.errMsg);
// #ifdef MP-WEIXIN
log.error('獲取用戶登錄態(tài)失敗!' + res.errMsg);
// #endif
}
this.globalData.isLogin = true;
},
fail: (err) => {
console.log('登陸失敗', err);
uni.hideLoading();
uni.showToast({
title: '登錄失敗',
icon: 'none',
});
// #ifdef MP-WEIXIN
log.error('小程序授權(quán)登錄失敗', err);
// #endif
},
});
},
index.vue
if (app.globalData.token) {
console.log('首頁(yè)有token', v);
this.init();
} else {
// 聲明回調(diào)函數(shù)獲取app.js onLaunch中接口調(diào)用成功后設(shè)置的 globalData 數(shù)據(jù)
console.log('首頁(yè)沒有token', app);
app.testDataCallback = (res) => {
console.log('首頁(yè)登錄后執(zhí)行init');
this.init();
};
}
https://blog.csdn.net/wsln_123456/article/details/109464578
https://juejin.cn/post/6844904104456634382