WxApp/page/component/index.js

99 lines
2.7 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

const app = getApp()
Page({
data: {
imgUrls: ["/image/b1.jpg", "/image/b2.jpg", "/image/b3.jpg"],
indicatorDots: false,
autoplay: false,
interval: 3000,
duration: 800,
goods: {},
},
onLoad() {
var self = this
self.checkUserProfile()
self.getUserProfile()// //获取openId
/**
* 发起请求获取商品列表信息
*/
wx.request({
// get请求
url: app.globalData.baseUrl + "/goods/loadData",
success(res) {
self.setData({
goods: res.data.data,
})
},
})
},
/**
* 检查本地缓存中是否有用户信息
*/
checkUserProfile() {
const userInfo = wx.getStorageSync('userInfo');
if (userInfo) {
// 如果有用户信息,直接设置数据
this.setData({
thumb: userInfo.avatarUrl,
nickname: userInfo.nickName,
});
} else {
//如果本地没有存储用户信息则通过openId查数据库中是否已经注册
wx.request({
url: app.globalData.baseUrl + "/user/getById",
method: "GET",
data: {
openId: wx.getStorageSync('openid'),
},
success(res) {
console.log(res.data.data)
// 将用户信息存到 StorageSync
const userInfo = {
avatarUrl: res.data.data.avatarUrl,
nickName: res.data.data.username
};
wx.setStorageSync('userInfo', userInfo); // 存储到本地
},
fail: (err) => {
// 没有用户信息,提示用户登录授权
wx.showModal({
title: '温馨提示',
content: '请先登录!',
showCancel: false,
success: (res) => {
if (res.confirm) {
console.log(res)
wx.navigateTo({
url: '/page/component/login/login',
});
}
}
});
}
})
}
},
//获取openId
getUserProfile() {
//通过wx.login()获取登录凭证code
wx.login({
success: (res) => {
const wxConfig = {
appid: "wx865aefa5a7115ae0",
secret: "3f9849429894435abc935eea88178dfd",
code: res.code
}
wx.request({
url: "https://api.weixin.qq.com/sns/jscode2session?appid=" + wxConfig.appid + "&secret=" + wxConfig.secret + "&code=" + wxConfig.code + "&js_code=" + wxConfig.code + '&grant_type=authorization_code',
success: (res) => {
wx.setStorageSync('openid', res.data.openid);
},
fail: (err) => {
console.error('wx.login 失败', err);
}
})
},
})
},
})