微信小程序之小试牛刀
目录
1、介绍
1.1、个人用户信息
1.2、小程序的界面控件使用
1.3、内部使用的功能
1.4、总结
2、app
2.1、app.json
2.2、app.js
3、UserLogin
3.1、UserLogin.wxml
3.2、UserLogin.js
4、InstallAgreement
4.1、InstallAgreement.wxml
4.2、InstallAgreement.js
5、Signature
5.1、Signature.wxml
5.2、Signature.wxss
5.3、 Signature.js
6、主界面 index
6.1、index.wxml
6.2、index.js
7、getCurrentUserInfo
8、getPhoneNumber
9、GetOrderData
10、UploadData
下载链接:小程序测试
1、介绍
1.1、个人用户信息
如图所示,
- 获取当前用户信息,
- 手机号,
- 此用户提交到云数据库的内容的删除和查看,以openid为唯一标识索引
- 默认状态为未登录,授权登录以后保存登录信息
- 在登陆时获取的openid其实调用云函数就可以读取到,但是还是用传统方式尝试做了一下
1.2、小程序的界面控件使用
主要有
- 常见的label、button、
- 所在地区使用省市区的picker,
- 费用使用的是普通的picker
- 学生姓名的添加删除使用动态渲染wx:for
- 签字使用canvas,同时界面切换
- 阅读并同意使用navigator跳转到安全事项的页面
1.3、内部使用的功能
- 云开发自带的数据库添加/删除/更新/查看
- 云开发的存储功能
- 界面滑动条的使用
- 单次和周期定时器的使用
- 调用云函数时同步等待
1.4、总结
自我感觉是把小程序普通的功能都使用了,剩下的就是特殊的需要的时候使用和熟能生巧,可是自己学了一轮感觉使用的机会都没有啊,可恶
- 框架中框架、wxml、wxss都有所熟悉
- 组件中的image、canvas、tabbar、view、scroll-view、button、checkbox、input、label、picker
- 界面之间的切换、交互、本地数据存储、本地文件存储、图片、云开发、服务端的api
2、app
文件框架如图所示
2.1、app.json
主要功能:添加了tabBar
{"pages": ["pages/index/index","pages/UserLogin/UserLogin","pages/InstallAgreement/InstallAgreement","pages/Signature/Signature"],"window": {"backgroundTextStyle": "light","navigationBarBackgroundColor": "#fff","navigationBarTitleText": "Weixin","navigationBarTextStyle": "black"},"style": "v2","sitemapLocation": "sitemap.json",//此处开始添加"tabBar": {"color": "#999","selectedColor": "#3D98FF","backgroundColor": "#fff","borderStyle": "white","list": [{"pagePath": "pages/index/index","iconPath": "image/icon_component.png","selectedIconPath": "image/icon_component_HL.png","text": "注册"},{"pagePath": "pages/UserLogin/UserLogin","iconPath": "image/icon_API.png","selectedIconPath": "image/icon_API_HL.png","text": "我的"}]}}
2.2、app.js
主要功能:添加了全局变量以及启动时读取
// app.js
App({globalData:{//全局变量phone: '',userInfo: {},userOpenid: '',hasUserInfo: false,hasPhoneNumber: false},onLaunch(){wx.cloud.init({env: '此处应当指定自己的云环境变量'})//全局变量的初始化const userinfo = wx.getStorageSync('userinfo') || {}const phoneNumber = wx.getStorageSync('phone') || ''const openid = wx.getStorageSync('openid') || ''this.globalData.userInfo = userinfo;this.globalData.userOpenid = openid;this.globalData.phone = phoneNumber;this.globalData.hasUserInfo = Object.keys(userinfo).length == 0?false:true;this.globalData.hasPhoneNumber = phoneNumber==''?false:true;},
})
3、UserLogin
3.1、UserLogin.wxml
主要功能:如果已登录显示用户信息和提交记录和删除记录,否则显示登录按钮
<view class="container"><view class="userinfo"><!-- 授权前 --><block wx:if="{{!hasUserInfo}}"><button type="primary" bindtap="getUserProfile" > 快速登录 </button></block><!-- 授权后 --><block wx:else><view class="users"><image class="userinfo-avatar" src="{{userInfo.avatarUrl}}" mode="cover"></image><text class="userinfo-nickname">{{userInfo.nickName}}</text><block wx:if="{{!hasPhoneNumber}}"><button type="primary" open-type="getPhoneNumber" bindgetphonenumber="getPhoneNumber">绑定手机号</button></block><block wx:else><text class="userinfo-phone">手机号: {{phone}}</text></block><view class="weui-btn-area"><button id="Buttom" class="weui-btn" type="primary"bindtap='ClickSubmitHistory' >提交记录</button><button id="Buttom" class="weui-btn" type="primary"bindtap='ClickRemove' >删除记录</button></view></view></block></view>
</view>
3.2、UserLogin.js
var global = getApp().globalData;
Page({data: {phone: '',userInfo: {},userOpenid: '',hasUserInfo: false,hasPhoneNumber: false},onLoad(options) {this.setData({userInfo: global.userInfo,userOpenid: global.userOpenid,phone: global.phone,hasPhoneNumber: global.hasPhoneNumber,hasUserInfo: global.hasUserInfo})},ClickSubmitHistory(res){wx.cloud.callFunction({name: 'GetOrderData',data: {Type: 'Get',userOpenid: global.userOpenid,}}).then(res =>{console.log("获取成功: ",res)}).catch(res => {console.log("获取失败: ",res)})},ClickRemove(res){wx.cloud.callFunction({name: 'UploadData',data: {Type: 'Remove',userOpenid: global.userOpenid,}}).then(res =>{console.log("删除成功: ",res)}).catch(res => {console.log("删除失败: ",res)})},async getPhoneNumber(res) {const errMsg = res.detail.errMsgif (errMsg != "getPhoneNumber:ok"){wx.showToast({title: '授权失败',icon: 'error'})return}const cloudId = res.detail.cloudIDconst cloudIdList = [cloudId]wx.showLoading({title: '获取中',mask: true})const cloudFunRes = await wx.cloud.callFunction({name: "getPhoneNumber",data: {cloudIdList:cloudIdList,openid: this.data.userOpenid}})console.log("cloudIdList: ",cloudIdList)console.log("cloudFunRes: ",cloudFunRes)const jsonStr = cloudFunRes.result.dataList[0].jsonconst jsonData = JSON.parse(jsonStr)const phoneNumber = jsonData.data.phoneNumberconsole.log(phoneNumber)this.setData({hasPhoneNumber: phoneNumber==''?false:true,phone: phoneNumber})this.globalData.phone = this.data.phone;this.globalData.hasPhoneNumber = this.data.hasPhoneNumber;wx.setStorageSync('phone', phoneNumber)wx.hideLoading({success: (res) => {},})},async getUserProfile(e) {var than = thiswx.getUserProfile({desc: '用于获取用户个人信息',success: function (detail) {wx.login({success: res => {var code = res.code; //登录凭证wx.cloud.callFunction({name: "getCurrentUserInfo",data: {encryptedData: detail.encryptedData,iv: detail.iv,code: code,userInfo: detail.rawData}}).then(res => {console.log("res: ",res);var openid = res.result.openid;var status = res.result.status;var phoneNumber = res.result.phone;console.log("openid: ",openid);console.log("status: ",status);console.log("phone: ",phoneNumber);console.log("nickName: ",detail.userInfo.nickName);wx.setStorageSync('userinfo', detail.userInfo)wx.setStorageSync('openid', openid)if(phoneNumber==undefined){wx.setStorageSync('phone', "")}else{wx.setStorageSync('phone', phoneNumber)}than.setData({userOpenid: openid,userInfo: detail.userInfo,hasUserInfo: true,hasPhoneNumber: phoneNumber==undefined?false:true,phone: phoneNumber==undefined?'':phoneNumber})this.globalData.userOpenid = this.data.userOpenid;this.globalData.userInfo = this.data.userInfo;this.globalData.hasUserInfo = this.data.hasUserInfo;this.globalData.hasPhoneNumber = this.data.hasPhoneNumber;this.globalData.phone = this.data.phone;}).catch(res => {console.log("111res3: ",res);})}});},fail: function () {wx.showModal({content: '取消授权将会影响相关服务,您确定取消授权吗?',success (res) {if (res.confirm) {wx.showToast({title: '已取消授权',duration: 1500})} else if (res.cancel) {this.getUserProfile()}}})}})}
})
4、InstallAgreement
主要功能:显示安全要求须知,没有任何行为,只有返回之前界面
4.1、InstallAgreement.wxml
<view catchtouchmove="catchtouchmove" class="tips" ><view class="tips_box"><view class="hint_view"><view class="text"><view class="hint1">出游须知</view><view class="hint2"><text>注意安全</text></view><view class="hint2"><text>危险时电话: 110</text></view><view class="hint2"><text>火灾时电话: 119</text></view><view class="hint2"><text>受伤时电话: 120</text></view></view></view><button bindtap='tipAgree' class="login" type='primary' formType="submit" >关闭</button></view></view>
4.2、InstallAgreement.js
Page({onLoad(options) {},tipAgree: function() { //重新画wx.navigateBack()},
})
5、Signature
主要功能:签名,返回临时文件图片的src
5.1、Signature.wxml
<view class="sign"><view class="paper"><canvas class="handWriting" disable-scroll="true" bindtouchstart="touchstart1" bindtouchmove="touchmove1" canvas-id="handWriting1"></canvas></view><view class="signBtn"><button size="" type="primary" bindtap="sign1ok">完成签字</button> <button size="" type="warn" bindtap="reSign1">重新签字</button></view>
</view>
5.2、Signature.wxss
.paper{border:1px solid #dedede; margin: 10px; height:200px }
.image{border:1px solid #dedede; margin: 10px; height:200px }
.signBtn{display: flex; margin-top:20px;}
.signTitle{ text-align: center; font-size:1.2em;margin:10px auto;}
.handWriting{width:100%; height:200px }
.image image{width:100%; height:200px }
5.3、 Signature.js
Page({data: {context1: null,hasDraw:false, //默认没有画src:null},onLoad: function() {console.log("Signature/onLoad")var context1 = wx.createCanvasContext('handWriting1');context1.setStrokeStyle("#000000")context1.setLineWidth(3);this.setData({src:null,context1: context1,})},touchstart1: function(e) {var context1 = this.data.context1;context1.moveTo(e.touches[0].x, e.touches[0].y);this.setData({context1: context1,hasDraw : true, //要签字了});},touchmove1: function(e) {var x = e.touches[0].x;var y = e.touches[0].y;var context1 = this.data.context1;context1.setLineWidth(3);context1.lineTo(x, y);context1.stroke();context1.setLineCap('round');context1.draw(true);context1.moveTo(x, y);},reSign1: function() { //重新画var that = this;var context1 = that.data.context1;context1.draw(); //清空画布that.setData({hasDraw: false, //没有画src: null});},sign1ok: function () {var that = this;if(!that.data.hasDraw){console.log("签字是空白的 没有签字")}else{var context1 = that.data.context1;context1.draw(true, wx.canvasToTempFilePath({canvasId: 'handWriting1',success(res) {console.log(res.tempFilePath) //得到了图片下面自己写上传吧var pages = getCurrentPages();var prevPage = pages[pages.length - 2];prevPage.setData({imageSource: res.tempFilePath})wx.navigateBack()}}))}},
});
6、主界面 index
6.1、index.wxml
<!--index.wxml--><view id="Top" class="page-body"><view class="page-section"><view class="weui-cells__title">带队老师</view><view class="weui-cells weui-cells_after-title"><view class="weui-cell weui-cell_input"><input class="weui-input" bindinput='SlotInput' data-cmd="Teacher" value="{{Teacher}}" auto-focus /></view></view><view class="weui-cells__title">联系人电话</view><view class="weui-cells weui-cells_after-title"><view class="weui-cell weui-cell_input"><input class="weui-input" bindinput='SlotInput' data-cmd="Phone" value="{{Phone}}" /></view></view><view class="weui-cells__title">班级</view><view class="weui-cells weui-cells_after-title"><view class="weui-cell weui-cell_input"><input class="weui-input" bindinput='SlotInput' data-cmd="Class" value="{{Class}}" /></view></view><view class="weui-cells__title">所在地区</view><view class="weui-cells weui-cells_after-title"><view class="section"><picker mode="region" bindchange="bindRegionChange" value="{{region}}" custom-item="{{customItem}}"><view class="picker">{{region[0]}} {{region[1]}} {{region[2]}}</view></picker></view></view><view class="weui-cells__title">具体地址</view><view class="weui-cells weui-cells_after-title"><view class="weui-cell weui-cell_input"><input class="weui-input" bindinput='SlotInput' data-cmd="Addr" value="{{Addr}}" /></view></view><view class="weui-cells__title">费用</view><view class="weui-cells weui-cells_after-title"><view class="section"><picker bindchange="bindPickerChange" value="{{ChargeModeIndex}}" range="{{ChargeModeList}}"><view class="picker">{{ChargeModeList[ChargeModeIndex]}} </view></picker></view></view><block wx:for="{{StudentNameList}}" wx:key="key"><view class="weui-cells__title">学生姓名{{index+1}}</view><view class="weui-cells weui-cells_after-title"><view class="weui-cell weui-cell_input"><input class="weui-input" bindinput='SlotInput' data-id="{{index}}" data-cmd="Student" value="{{StudentNameList[index]}}" /></view></view></block > <button class='AddStudent' bindtap='AddStudent'>添加</button><button class='DelStudent' bindtap='DelStudent'>删除</button><view class="weui-cell weui-cell_input" hidden="{{imageSource?true:false}}"><input class="weui-input" style="width:100%;height:200px" bindfocus='ClickImage' placeholder="请在此处点击签字" /></view><view class="image" hidden="{{imageSource?false:true}}"><image src="{{imageSource}}" style="width:100%;height:200px"></image></view></view><!--相关协议--><checkbox-group bindchange="bindAgreeChange"><label class="weui-agree" for="weuiAgree"><view class="weui-agree__text"><checkbox class="weui-agree__checkbox" id="weuiAgree" value="agree" checked="{{}}" /><view class="weui-agree__checkbox-icon"><icon class="weui-agree__checkbox-icon-check" type="success_no_circle" size="9" wx:if="{{isAgree}}"></icon></view>阅读并同意<navigator url="/pages/InstallAgreement/InstallAgreement" class="weui-agree__link">《安全事项》</navigator></view></label></checkbox-group>
<!--提交按钮-->
<view class="weui-btn-area"><button id="Buttom" class="weui-btn" type="primary"bindtap='ClickSubmit'disabled='{{btn_disabled}}'>确定提交</button>
</view>
</view>
6.2、index.js
var global = getApp().globalData;
Page({data: {SendTimeOutCount: 0,SendTimeOutTimerID: 0,scrollPos: 0,isAgree: 0,btn_disabled: true,cmd: '',Teacher: 'baidu',Phone: '12345678910',Class: '初三一班',region: ['北京市', '北京市', '海淀区'],Addr: '西北旺东路10号院百度科技园1号楼',ChargeModeIndex: 1,ChargeModeList: ['','自费', '免费'],StudentNameList: ['小明','小红','小黄'],imageSource: null,UploadDataResult: false},CurrentPageScrollTo(in_data){var timer = setTimeout(()=>{ wx.pageScrollTo({ selector: in_data});clearTimeout(timer);},500)},onPageScroll:function(e){ // 获取滚动条当前位置this.data.scrollPos = e.scrollTop},onShow(){console.log("index/onShow ")if(this.data.scrollPos < 100){this.CurrentPageScrollTo('#Top')}else{this.CurrentPageScrollTo('#Buttom')}},onUnload(){if(this.data.SendTimeOutTimerID != 0){clearInterval(this.data.SendTimeOutTimerID)}},onLoad() {},bindPickerChange: function (e) {console.log('收费模式发送选择改变,携带值为', e.detail.value)this.setData({ChargeModeIndex: e.detail.value})this.data.Model = this.data.ChargeModeList[e.detail.value]},bindRegionChange: function (e) {console.log('所在地区发送选择改变,携带值为', e.detail.value)this.setData({region: e.detail.value})},SlotInput(res){console.log(res);var than = this;let InputCmd = res.currentTarget.dataset.cmd;let val = res.detail.value;switch(InputCmd){case 'Teacher':than.data.Teacher = val;break;case 'Phone':than.data.Phone = val;break;case 'Class':than.data.Class = val;break;case 'Addr':than.data.Addr = val;break;case 'Student':let ClickIndex = res.currentTarget.dataset.id;than.data.StudentNameList[ClickIndex] = val;break;}},AddStudent: function(){var lists = this.data.StudentNameList;if(lists.length > 15){wx.showToast({title: '超出最大限制',//用户看到的提示信息icon: 'none',//提示图标,有error,success、noneduration: 2000//停留时间})return}var newData = '';lists.push(newData);this.setData({StudentNameList: lists,}) console.log(this.data.StudentNameList)},DelStudent: function () {var lists = this.data.StudentNameList;lists.pop();this.setData({StudentNameList: lists,})console.log(this.data.StudentNameList)},ClickImage: function(){wx.navigateTo({url: '/pages/Signature/Signature',})},bindAgreeChange:function(e) {console.log(e.detail.value)this.setData({isAgree:e.detail.value.length,})if (e.detail.value.length==1){this.setData({btn_disabled:false,})}else{//onsole.log(e.detail.value.length)this.setData({btn_disabled:true})}},CheckData(){var ErrorString = ''if(this.data.Teacher.replace(/\s+/g, '') == ''){ErrorString = '带队老师为空'}else if(this.data.Phone.replace(/\s+/g, '') == ''){ErrorString = '联系人电话为空'}else if(this.data.Class.replace(/\s+/g, '') == ''){ErrorString = '班级为空'}else if(this.data.region.join("") == ''){ErrorString = '所在地区为空'}else if(this.data.Addr.replace(/\s+/g, '') == ''){ErrorString = '具体地址为空'}else if(this.data.ChargeModeList[this.data.ChargeModeIndex].replace(/\s+/g, '') == ''){ErrorString = '费用模式为空'}else if(this.data.imageSource == null){ErrorString = '当前还未签字确认'}else{let StudentNameListLen = this.data.StudentNameList.lengthconsole.log("StudentNameListLen: " ,StudentNameListLen)if(StudentNameListLen == 0){ErrorString = '学生姓名存在为空'return ErrorString;}for(let i = 0;i < StudentNameListLen;i++){if(this.data.StudentNameList[i].replace(/\s+/g, '') == ''){ErrorString = '学生姓名存在为空'return ErrorString;}}ErrorString = ''}return ErrorString},SendTimeOutTimerCheck(){// console.log("Time: " ,time.formatTime(new Date()));this.data.SendTimeOutCount++;if(this.data.SendTimeOutCount > 60){if(this.data.SendTimeOutTimerID != 0){clearInterval(this.data.SendTimeOutTimerID)}this.data.SendTimeOutCount = 0;wx.hideLoading({})wx.showToast({title: '获取超时',//用户看到的提示信息icon: 'none',//提示图标,有error,success、none})}else{if(this.data.UploadDataResult == true){if(this.data.SendTimeOutTimerID != 0){clearInterval(this.data.SendTimeOutTimerID)}this.data.SendTimeOutCount = 0;wx.hideLoading({})wx.showToast({title: '提交成功',//用户看到的提示信息icon: 'success',//提示图标,有error,success、none})}}},ClickSubmit:function(e){console.log(global.userOpenid)if(global.userOpenid == ''){wx.showToast({title: '当前还未登录',//用户看到的提示信息icon: 'error',//提示图标,有error,success、noneduration: 2000//停留时间})}var ErrorString = this.CheckData()if(ErrorString != ''){wx.showToast({title: ErrorString,//用户看到的提示信息icon: 'none',//提示图标,有error,success、noneduration: 2000//停留时间})return}this.UploadDataToCloudService()this.data.SendTimeOutTimerID = setInterval(this.SendTimeOutTimerCheck,1000)wx.showLoading({title: '请稍等',})},async UploadDataToCloudService(){let status = false;let result1 = await wx.cloud.callFunction({name: 'UploadData',data: {Type: 'Upload',Teacher: this.data.Teacher,Phone: this.data.Phone,Address: this.data.region.join("") + this.data.Addr,ChargeMode: this.data.ChargeModeList[this.data.ChargeModeIndex],StudentNameList: this.data.StudentNameList.join(","),userOpenid: global.userOpenid,}});var path = 'Signature/'path += this.data.StudentNameList.join("|")path += '.png'let result2 = await wx.cloud.uploadFile({cloudPath: path, // 上传至云端的路径filePath: this.data.imageSource, // 小程序临时文件路径})console.log('调用云函数结果,status:',status);console.log('调用云函数结果,result1:',result1);console.log('调用云函数结果,result2:',result2);if(result1.result.result == "Submit success!" && result2.statusCode == 204){this.data.UploadDataResult = true;}},
})
7、getCurrentUserInfo
主要功能:获取openid,其实使用云开发没有必要、已经自带了
const request = require('request')
// 云函数入口文件
const cloud = require('wx-server-sdk')cloud.init({env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database()
// 云函数入口函数
let user_id;
let user_uid;
exports.main = async (event, context) => {const wxContext = cloud.getWXContext()let code = event.code;//获取小程序传来的codelet encryptedData = event.encryptedData;//获取小程序传来的encryptedDatalet iv = event.iv;//获取小程序传来的ivlet userInfo = JSON.parse(event.userInfo) //获取个人信息let appid = "xxxxxxxxxxx";//自己小程序后台管理的appid,可登录小程序后台查看let secret = "xxxxxxxxxxx";//小程序后台管理的secret,可登录小程序后台查看let grant_type = "authorization_code";// 授权(必填)默认值let url = "https://api.weixin.qq.com/sns/jscode2session?grant_type="+grant_type+"&appid="+appid+"&secret="+secret+"&js_code="+code;const stat = await new Promise((resolve, reject) => {request(url, (err, response, body) => {if (!err && response.statusCode == 200) {let _data = JSON.parse(body)let UserCount = 0;user_id = _data.openiduser_uid = _data.unioniddb.collection('Account').where({user_id: _data.openid // 填入当前用户 openid}).count().then(res => {UserCount = res.total;if(UserCount == 0){/* 插入当前列表 */db.collection('Account').add({data: {user_id: _data.openid,nickName: userInfo.nickName,avatarUrl: userInfo.avatarUrl,gender: userInfo.gender,phone: ''}}).then(res => {resolve("Insert success!");}).catch(res => {reject("Insert fail!");})}else if(UserCount == 1){/* 更新当前列表 */db.collection('Account').where({user_id: _data.openid // 填入当前用户 openid}).update({data: {nickName: userInfo.nickName,avatarUrl: userInfo.avatarUrl,gender: userInfo.gender}}).then(res => {resolve("Update success!");}).catch(res => {reject("Update fail!");})}else if(UserCount > 1){/* 删除所有此id的并且重新添加 */db.collection('Account').where({user_id: _data.openid // 填入当前用户 openid}).remove().then(res => {db.collection('Account').add({data: {user_id: _data.openid,nickName: userInfo.nickName,avatarUrl: userInfo.avatarUrl,gender: userInfo.gender,phone: ''}})resolve("Remove and insert success!");}).catch(res => {reject("Remove fail!");})}})}})})const CurrentPhoneObject = await db.collection('Account').where({user_id: user_id // 填入当前用户 openid}).get()const CurrentPhone = CurrentPhoneObject.data[0].phoneconsole.log("CurrentPhone: ",CurrentPhone);console.log("stat: ",stat);console.log("user_id: ",user_id);console.log("user_uid: ",user_uid);return {status: stat,CurrentPhone: CurrentPhone,openid: user_id,unionid: user_uid}
}
8、getPhoneNumber
主要功能:获取手机号码
const cloud = require('wx-server-sdk')cloud.init({env: cloud.DYNAMIC_CURRENT_ENV
})const db = cloud.database()
// 云函数入口函数
exports.main = async (event) => {const wxContext = cloud.getWXContext()console.log("event: ",event)const openid = event.openidconst cloudIdList = event.cloudIdListconsole.log("openid: ",openid)console.log("openid: ",wxContext.OPENID)console.log("cloudIdList: ",cloudIdList)try {const result = await cloud.openapi.cloudbase.getOpenData({openid: openid,cloudidList: cloudIdList})const jsonStr = result.dataList[0].jsonconst jsonData = JSON.parse(jsonStr)const phoneNumber = jsonData.data.phoneNumberconsole.log("phoneNumber: ",phoneNumber)await db.collection('Account').where({user_id: openid // 填入当前用户 openid}).update({data: {phone: phoneNumber}}).then(res => {console.log("Update success!");}).catch(res => {console.log("Update fail!");})return result} catch (err) {return err}
}
9、GetOrderData
主要功能:获取所有此用户的提交信息
// 云函数入口文件
const cloud = require('wx-server-sdk')cloud.init({env: cloud.DYNAMIC_CURRENT_ENV
})// 云函数入口函数
const MAX_LIMIT = 100
const db = cloud.database()
exports.main = async (event, context) => {let OptionsType = event.Type;let userOpenid = event.userOpenid;const countResult = await db.collection('Orders').where({userOpenid: userOpenid // 填入当前用户 openid}).count()const total = countResult.totalconst batchTimes = Math.ceil(total / 100)// 承载所有读操作的 promise 的数组const tasks = []for (let i = 0; i < batchTimes; i++) {const promise = db.collection('Orders').where({userOpenid: userOpenid}).skip(i * MAX_LIMIT).limit(MAX_LIMIT).get()tasks.push(promise)}// 等待所有return (await Promise.all(tasks)).reduce((acc, cur) => {return {data: acc.data.concat(cur.data),errMsg: acc.errMsg,}})
}
10、UploadData
主要功能:删除和添加
// 云函数入口文件
const cloud = require('wx-server-sdk')cloud.init({env: cloud.DYNAMIC_CURRENT_ENV
})const db = cloud.database()
exports.main = async (event, context) => {let OptionsType = event.Type;let userOpenid = event.userOpenid;let result;console.log('start...');if(OptionsType == 'Get'){const countResult = await db.collection('Orders').where({userOpenid: userOpenid // 填入当前用户 openid}).count()const total = countResult.total}console.log('break2...');result = await new Promise((resolve, reject) => {if(OptionsType == 'Upload'){db.collection('Orders').add({data:{Teacher: event.Teacher,Phone: event.Phone,Address: event.Address,ChargeMode: event.ChargeMode,StudentNameList: event.StudentNameList,userOpenid: event.userOpenid}}).then(res => {resolve("Submit success!");}).catch(res => {reject("Submit fail!");})}else if(OptionsType == 'Remove'){db.collection('Orders').where({userOpenid: userOpenid // 填入当前用户 openid}).remove().then(res => {resolve("Remove success!");}).catch(res => {reject("Remove fail!");})}else if(OptionsType == 'Get'){// const countResult = db.collection('Orders').where({// userOpenid: userOpenid // 填入当前用户 openid// }).count()// const total = countResult.total// console.log('total: ',total);// console.log('countResult: ',countResult);// const MAX_LIMIT = 100// const total = countResult.total// console.log('total: ',total);// // 计算需分几次取// const batchTimes = Math.ceil(total / 100)// // 承载所有读操作的 promise 的数组// const tasks = []// for (let i = 0; i < batchTimes; i++) {// const promise = db.collection('todos').skip(i * MAX_LIMIT).limit(MAX_LIMIT).get()// tasks.push(promise)// }// // 等待所有// return (await Promise.all(tasks)).reduce((acc, cur) => {// return {// data: acc.data.concat(cur.data),// errMsg: acc.errMsg,// }// })resolve("Nothing");}})return {event,result: result}
}
下载链接:小程序测试
微信小程序之小试牛刀相关推荐
- iKcamp出品|微信小程序|小试牛刀(视频)+发布流程|基于最新版1.0开发者工具初中级教程分享
iKcamp官网:http://www.ikcamp.com 访问官网更快阅读全部免费分享课程:<iKcamp出品|全网最新|微信小程序|基于最新版1.0开发者工具之初中级培训教程分享>. ...
- 微信小程序基于最新版1.0开发者工具分享-小试牛刀(视频) 发布流程
第一章:小程序初级入门教程 小试牛刀[含视频] 视频地址:https://v.qq.com/x/page/i0554akzobq.html 这一章节中,我们尝试着写一个最简单的例子,包含 2 个静态页 ...
- iKcamp出品|全网最新|微信小程序|基于最新版1.0开发者工具之初中级培训教程分享...
?? 微信小程序课程,面向所有具备前端基础知识的同学 ?? iKcamp官网:http://www.ikcamp.com 访问官网更快阅读全部免费分享课程:<iKcamp出品|全网最新|微信小程 ...
- 微信小程序之旅一(注册页面的使用)
每个页面文件夹里都对有对应的一个js文件,在这个文件夹李的page()函数用于注册一个页面.接受一个object参数,具体object参数如下: 属性 类型 说明 data Object 页面初 ...
- 微信小程序之旅一(页面渲染)
1.微信小程序条件渲染(wx:if):使用wx:if={{Boolean}}来判断是否需要渲染该代码块,使用wx:elif和wx:eise来渲染else块 <view wx:if="{ ...
- 【微信小程序】微信小程序入门与实战-个人笔记
微信小程序入门与实战 文章目录 微信小程序入门与实战 1 初识微信小程序 1-1 2020版重录说明 1-2 下载小程序开发工具 1-3 新建小程序项目 1-4 小程序appid的注册 1-5 新版小 ...
- 微信小程序全方位解析
九个月之前,应用号首次被提出.近日,应用号以"小程序"的名称,正式向200人发出公测邀请."无需下载,用完即走",微信小程序提供了一种新的开放能力,使其在IT圈 ...
- 微信小程序云开发快速入门手册-告别切图仔的时刻到了
文章很长,建议先收藏,有充分的时间再学习,没有小程序基础的,也阔以先收藏哦. 本文章会手把手带各位小伙伴入门微信小程序云开发,因为我还不是全栈工程师,所以不是特别清楚前后端分离模式下,后端工程师需 ...
- 微信小程序根据日期和时间进行排序
一.前言 最近接手了一个小程序的项目,有这样一个需求要对列表进行日期和时间的排序,于是小试牛刀,操作了一番,终于搞出来,在这里给大家总结分享一下经验,希望对大家有一定的帮助. 二.需求分析(这是已完成 ...
最新文章
- manjaro mysql_如何看待manjaro的软件仓库连个mysql都没有?
- ftime()函数的用法----算函数运行时间
- “Zhuang.Data”轻型数据库访问框架(二)框架的入口DbAccessor对象
- 坑爹的SQL ISNUMERIC
- android 从图片获取二维码
- C++实现有序表折半查找
- 比较创建几种线程的方式
- Module System of Swift (简析 Swift 的模块系统)
- python爬取b站排行榜_实时爬取B站排行榜并保存为表格——每周一个爬虫小教程系列...
- 如何使用开源工具制作YouTube系列
- 项目管理工具project软件学习(八) - 关键路径查询、资源可用性
- oracle取第一位,Oracle中的substr()函数和INSTR()函数
- Spark Group
- LeetCode 20 Valid Parentheses (C++)
- mysql自增序列nextval并发_[DB][MySql]关于取得自增字段的值、及@@IDENTITY 与并发性问题...
- html写注册协议页面,html+css编写用户注册协议页
- 把数字倒序的几种方法(二更,增加了负数反序的情况)(c++)
- Python之web服务利器Flask生产环境部署实践【基于gunicorn部署生产环境】
- 计算机切换用户神魔意思,快速切换用户是什么意思?
- 华为OD机试 - 士兵过河
热门文章
- @高校学生开发者,为什么你一定要“上手”开源项目?
- 【mongoDB基础篇①】安装与常用操作语句
- PHP快速入门02-PHP语言基础
- word常见问题_3 批量修改图片大小
- 【图像配准】图像配准基础知识:入门知识、点云基础、图像配准的概念、基础和分类
- 百思不得其解的Failed to allocate a managed memory buffer of 268435456 bytes.错误解决
- 小黄豆CRM v1.17版本发布
- 离职的腾讯5万名员工创办了1372家公司,如今他们都咋样了?
- 教师计算机知识比赛方案,教师计算机基础知识考核方案.doc
- 彭于晏简单网页制作(HTML和css)