实现登录功能的代码
html如下
<view class="center">
<view class="userInfo">
<view class="avatar">
<image wx:if="{{avatar}}" src="{{avatar}}"></image>
<image wx:else src="../../image/avatar.png" bindtap="login"></image>
</view>
<view class="info">
<button wx:if="{{!nickName}}" class="button" bindtap="login" >点击登录</button>
<block wx:else>
<view class="nickName">{{nickName}}</view>
<view class="mobile">很高兴认识你</view>
</block>
</view>
</view>
</view>
再来看下js
// pages/center/index.js
Page({
/**
* 页面的初始数据
*/
data: {
avatar:'',
nickName:''
},
/**
* 生命周期函数--监听页面加载
*/
onLoad() {
if(wx.getStorageSync('avatar')||wx.getStorageSync('nickName'))
this.setData({
avatar:wx.getStorageSync('avatar'),
nickName:wx.getStorageSync('nickName')
})
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady() {
},
login(){
wx.cloud.callFunction({
name: 'getopenid',
})
.then(res => {
let openid = res.result.openid
if(openid){
wx.getUserProfile({
desc: '用于完善会员资料',
success:(res)=>{
let nickName = res.userInfo.nickName
let avatar = res.userInfo.avatarUrl
let data = {
nickName:nickName,
avatar:avatar
}
wx.setStorageSync('nickName', res.userInfo.nickName)
wx.setStorageSync('avatar', res.userInfo.avatarUrl)
wx.cloud.callFunction({
name:'userLogin',
data:data
}).then(res=>{
console.log(res)
})
this.setData({
avatar:res.userInfo.avatarUrl,
nickName:res.userInfo.nickName
})
}
})
}
// console.log("云函数获取成功", res.result.data);
})
.catch(res => {
console.log("云函数获取失败", res);
})
},
/**
* 生命周期函数--监听页面显示
*/
onShow() {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide() {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload() {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh() {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom() {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage() {
}
})
然后来看下云函数
// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init({
env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database()
// 云函数入口函数
exports.main = async (event, context) => {
const wxContext = cloud.getWXContext()
let user = db.collection('zhusir_huiyuan')
let {total} = await new Promise( (resolve, reject)=>{
user.where({ _openid: wxContext.OPENID }).count().then( res=>{
resolve(res)
})
})
let data = {
_openid: wxContext.OPENID,
updateTime:new Date().getTime(),
avatar:event.avatar,
nickName:event.nickName
}
if( total == 0 ){
console.log(data)
data.createTIme =new Date().getTime()
return await user.add({ data }).then( res=>{
console.log('新增成功->', res)
return res
}).catch( err=>{
console.log('新增失败',err)
})
}else{
return await user.where({ _openid: wxContext.OPENID }).update({ data }).then( res=>{
console.log('更新成功->', res)
return res
}).catch( err=>{
console.log('更新失败',err)
})
}
}
咱们需要的oopenid来自于另外一个云函数