初次接觸微信小程序进倍,到現(xiàn)在經(jīng)歷了兩個(gè)項(xiàng)目揉阎,所幸一直用的都是vue,學(xué)習(xí)陡度較低背捌,在這里記錄一下自己在微信小程序里遇到過(guò)的問(wèn)題毙籽。
1.app.js的執(zhí)行順序低于index.js。所以如果你在app.js寫(xiě)微信授權(quán)和登錄的獲取用戶(hù)信息的話毡庆,index.js獲取到的用戶(hù)信息是null坑赡,當(dāng)然你也可以將微信登陸擋在index。js中么抗,但是這種方法不適用有分享功能的微信小程序毅否,所以,我的辦法是:
在app蝇刀。js中將微信登陸封裝成函數(shù)模塊螟加,然后再index。js中調(diào)用吞琐,需要注意的是捆探,封裝的函數(shù)需要做一個(gè)判斷,判斷本地存儲(chǔ)有無(wú)用戶(hù)信息站粟,有則return黍图,無(wú)則執(zhí)行方法。
logins: function (success) {
let _this = this
if (wx.getStorageSync("userid")) {
_this.globalData.userid= wx.getStorageSync("userid");
_this.globalData.userInfo= wx.getStorageSync("userInfo");
success();
console.log('有用戶(hù)信息奴烙,不登陸')
return;
}
console.log('沒(méi)有用戶(hù)信息助被,登陸')
// 登錄
wx.login({
success: function (res) {
// 發(fā)送 res.code 到后臺(tái)換取 openId, sessionKey, unionId
getApp().globalData.code = res.code;
wx.getUserInfo({
success: res => {
// 可以將 res 發(fā)送給后臺(tái)解碼出 unionId
_this.globalData.userInfo = res.userInfo
wx.setStorage({
key: 'userInfo',
data: res.userInfo,
})
console.log(getApp().globalData.userInfo)
let code = getApp().globalData.code
console.log(code, 11111111111)
wx.request({
url: 'http://',
data: {
act: 'wx_login',
op: 'resOpenId',
code: code,
encrypted_data: res.encryptedData,
iv: res.iv
},
method: "POST",
header: {
"Content-Type": "application/x-www-form-urlencoded"
},
success: function (res) {
console.log('登陸成功', res.data.res.userid)
wx.setStorage({
key: 'userid',
data: res.data.res.userid,
})
getApp().globalData.userid = res.data.res.userid;
success();
}, fail: function (res) {
console.log(res, '登陸失敗')
wx.showToast({
title: '登陸失敗',
icon:none
})
}
})
// 由于 getUserInfo 是網(wǎng)絡(luò)請(qǐng)求,可能會(huì)在 Page.onLoad 之后才返回
// 所以此處加入 callback 以防止這種情況
if (_this.userInfoReadyCallback) {
_this.userInfoReadyCallback(res)
console.log('callback')
}
},
fail: function (err) {
console.log("未授權(quán)");
wx.showModal({
title: '系統(tǒng)提示',
content: '您還未對(duì)《小游戲》授權(quán),是否立即前往授權(quán)切诀?',
success: function (res) {
if (res.confirm) {
console.log('用戶(hù)點(diǎn)擊確定')
wx.openSetting({
success: (res) => {
if (res.authSetting['scope.userInfo'] == true) {
//已授權(quán)
_this.logins(success);
} else {
//用戶(hù)任然未授權(quán)
}
}
})
} else if (res.cancel) {
console.log('用戶(hù)點(diǎn)擊取消')
//用戶(hù)任然未授權(quán)
}
}
})
}
})
}
});
}
溜了溜了
2 .