小程序云开发登录,存用户的数据到云数据库
代码:建立一个云函数getOpenid , 获取用户openid// 云函数入口文件const cloud = require('wx-server-sdk')cloud.init()// 云函数入口函数exports.main = async (event, context) => {const wxContext = cloud.getWXContext()return {event,o
·
代码:
建立一个云函数 getOpenid , 获取用户openid
// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init()
// 云函数入口函数
exports.main = async (event, context) => {
const wxContext = cloud.getWXContext()
return {
event,
openid: wxContext.OPENID,
appid: wxContext.APPID,
unionid: wxContext.UNIONID,
}
}
登录页面的wxml代码
<!--index.wxml-->
<view class="page" data-weui-theme="{{theme}}">
<view class="weui-form">
<view class="weui-form__text-area">
<image bindtap="bindViewTap" class="userinfo-avatar" src="../../img/LOGO.png" mode="cover"></image>
</view>
<view class="weui-cells weui-cells_after-title">
<radio-group bindchange="radioChange">
<label class="weui-cell weui-check__label" wx:for="{{items}}" wx:key="{{item.value}}">
<view class="weui-cell__hd">
<radio value="{{item.value}}" />
</view>
<view class="weui-cell__bd">{{item.name}}</view>
</label>
</radio-group>
</view>
<view class="weui-form__opr-area begin">
<button open-type="getUserInfo" bindgetuserinfo='getUserInfo' class="weui-btn submit weui-btn_primary">登录</button>
</view>
</view>
</view>
登录页面的js代码,
逻辑,调用云函数获取openid,录入用户的信息存到 user数据库表。
//index.js
//获取应用实例
const app = getApp();
var userInfo;
wx.cloud.init({
env: 'vclass-34p02'
})
const DB = wx.cloud.database()
var that;
Page({
data: {
userType:'',
items:[
{value: '我是学生', name: '我是学生'},
{value: '我是老师', name: '我是老师'}]
},
radioChange(e) {
console.log('radio发生change事件,携带value值为:', e.detail.value)
this.setData({
userType:e.detail.value
})
},
onLoad() {
that = this;
if(wx.getStorageSync('user')){
wx.switchTab({
url: '/pages/studycentre/studycentre',
})
}
},
userAdd(openId) {
var user = {
userType: this.data.userType,
nickName: userInfo.nickName,
avatarUrl: userInfo.avatarUrl,
openId: openId
};
wx.setStorageSync('user', user);
DB.collection('user').add({
// data 字段表示需新增的 JSON 数据
data: user
}).then(res => {
console.log(res)
wx.switchTab({
url: '/pages/studycentre/studycentre',
})
})
},
getUserInfo: function (e) {
if(!this.data.userType){
wx.showToast({
title: '选择身份后才可登录',
icon:'none'
})
return
}
console.log(e)
userInfo = e.detail.userInfo;
wx.cloud.callFunction({
name: "getOpenid",
success(res) {
let openId = res.result.openid
// 判断数据库中是否已经有数据
DB.collection('user').where({
openId: openId,
})
.get().then(ress => {
console.log('ressressressressressressressress',ress.data[0])
if (ress.data.length == 0) {
that.userAdd(openId)
} else {
wx.setStorageSync('user', ress.data[0]);
wx.switchTab({
url: '/pages/studycentre/studycentre',
})
}
})
},
fail(res) {
console.log('登录失败', res)
}
})
}
})
更多推荐
已为社区贡献17条内容
所有评论(0)