The mini-program just submitted has been approved. Send out the notes. Before a paragraph to see the circle of friends always someone with TXT record weight, especially want to write a record weight of the small program, now small program cloud development has cloud function, database, really good to use, very suitable for individual developers, server domain name nothing, cloud development let you do not have to worry about these things.
Take a look at the page image first:
- Global variable globalData
- The use of NPM
- Cloud function
- Database operations
- The use of async
- Shared configuration
- AntV use
- TabBar Indicates the address forwarding
- Switch page refresh
1. Global variable globalData
After the first login, store the openId for other pages to use, shared with globalData.
<! --app.js set globaldata. openid --> app ({onLaunch: function () {
this.globalData = {}
wx.cloud.init({})
wx.cloud.callFunction({
name: 'login'.data: {},
success: res= > {
this.globalData.openid = res.result.openid
wx.switchTab({
url: '/pages/add/add'.fail: function(e) {}})},fail: err= >{}})}}) <! -- Other page references -->const app = getApp() // Get the instance
app.globalData.openid // Just reference it
Copy the code
2. The use of NPM
- Enter the small program source code
miniprogram
Directory, createpackage.json
File (usingnpm init
All the way back) npm i --save
We’re going to install itnpm
package- Set up wechat developer tools to build
npm
package.json
increase"miniprogram": "dist"
If the package directory field is not set, uploading and previewing fail, indicating that the file package is too large.
cdMiniprogram NPM init NPM i@antv /f2-canvas --save // I used F2, can change to another packageCopy the code
Set up wechat developer tools
npm
Finally, be sure to add the miniProgram field
{
"name": "21Day"."version": "1.1.0"."miniprogram": "dist"."description": "A 21-day weight tracking app."."license": "MIT"."dependencies": {
"@antv/f2-canvas": "~ 1.0.5." "."@antv/wx-f2": "~ 1.1.4." "
},
"devDependencies": {}}Copy the code
3. The function of cloud
Cloud functions are functions that run in the cloud (server side). The server side is Node.js, which is JavaScript. There is an official database operation, but the updated operation requires the use of cloud functions. In addition, if the cloud function uses NPM package, remember to right-click in the cloud function folder to upload and deploy, otherwise the operation will fail.
Last example, update the weight of the cloud function
/ / cloud function
const cloud = require('wx-server-sdk')
const moment = require('moment')
cloud.init(
{ traceUser: true})const db = cloud.database()
const wxContext = cloud.getWXContext()
exports.main = async (event, context) => {
// event input parameter
delete event.userInfo
try {
return await db.collection('list').where({
_openid:wxContext.OPENID,
date:moment().format('YYYY-MM-DD')
})
.update({
data: {
...event
},
})
} catch(e) {
console.error(e)
}
}
Copy the code
Applet side call
wx.cloud.callFunction({
name: 'add'.data: {
...Param
},
success: res= > {
wx.showToast({
title: 'Record added successfully',}}),fail: err= > {
wx.showToast({
icon: 'none'.title: 'Failed to add record'})}})Copy the code
4. Perform database operations
In fact, access to MongoDB, encapsulated a part of the API, the details on the official document, there is a distinction between the server and small program segment.
const db = wx.cloud.database()
// Query data
db.collection('list').where({
_openid: app.globalData.openid,
date: moment().subtract(1.'days').format('YYYY-MM-DD'),
}).get({
success: function (res) {
// do someThing}})Copy the code
5. The use of async
async
regeneratorRuntime
npm i regenerator
node_modules
regenerator-runtime
runtime-module.js
runtime.js
lib
<! - case - >const regeneratorRuntime = require('.. /.. /lib/runtime.js')
onLoad: async function (options) {
// Get the data of the day
await this.step1()
// Set the time type
let nowHour = moment().hour(),timeType
nowHour > 12 ? timeType = 'evening' : timeType = 'morning'
this.setData({timeType})
}
Copy the code
6. Share configuration
Sharing is very simple, there is a distinction between the top right share and click the button to share
onShareAppMessage: function (res) {
// Share in the upper right corner
let ShareOption = {
title: '21 Days of Weight Loss '.path: '/pages/index/index',}// Button share
if(res.from == "button"){
ShareOption = {
title: 'Look at my weight loss record.'.path: '/pages/detail/detail? item=' + app.globalData.openid,
}
}
return ShareOption
}
Copy the code
After sharing, others click on the page, jump to the corresponding pages address, take the number of parameter requests from the options of onLoad
onLoad: function (options) {
const db = wx.cloud.database()
let This = this
let resault = {}
db.collection('list').where({
_openid: options.item
}).get({
success: function (res) {
resault = res.data
This.setData({
resault:resault
})
}
})
},
Copy the code
7. AntV use
The installation of antV is mentioned in the second section above, so I don’t need to talk about it and refer to it directly in the page.
To use this, you need to set up a global variable to store an instance of the diagram, and then modify the data using the changeData method in the hook function content.
The package name is introduced in index.json
{
"usingComponents": {
"ff-canvas": "@antv/f2-canvas"}}Copy the code
/ / introduction of F2
import F2 from '@antv/wx-f2';
// Set instance global variables (be sure)
let chart = null;
function initChart(canvas, width, height, F2) { // Use F2 to draw diagrams
let data = [
// {timestamp: '1951 ', step: 38},
];
chart = new F2.Chart({
el: canvas,
width,
height
});
chart.source(data, {
step: {
tickCount: 5
},
timestamp: {
tickCount: 8}}); chart.axis('timestamp', {
label(text, index, total) {
const textCfg = {};
if (index === 0) {
textCfg.textAlign = 'left';
}
if (index === total - 1) {
textCfg.textAlign = 'right';
}
returntextCfg; }}); chart.axis('step', {
label(text) {
return {
text: text / 1000 + 'step k'}; }}); chart.tooltip({showItemMarker: false,
onShow(ev) {
const { items } = ev;
items[0].name = null;
items[0].name = items[0].title;
items[0].value = items[0].value + 'step'; }}); chart.area().position('timestamp*step').shape('smooth').color('l zero (0) : # F2C587 0.5: # 1: ED7973 # 8659 af');
chart.line().position('timestamp*step').shape('smooth').color('l zero (0) : # F2C587 0.5: # 1: ED7973 # 8659 af');
chart.render();
return chart;
}
// Lifecycle functions
onLoad(){
// Assign values using changeData
chart.changeData(stepInfoList)
}
Copy the code
8. TabBar Indicates the address forwarding
NavigateTo: wx.navigateTo: wx.navigateTo: Wx. navigateTo: Wx.
wx.switchTab({
url: '/pages/add/add'.fail: function(e) {}
})
wx.navigateTo({
url: '.. /deployFunctions/deployFunctions',})Copy the code
9. Switch to page refresh
When you switch between several tabbars, you need to refresh the data. Just call the onLoad method in the onShow method.
onShow: function () {
this.onLoad()
}
Copy the code
feeling
- Very suitable for individual developers, want to develop a small program, in addition to the time, completely no other costs
- Error prompt is not friendly, sometimes do not execute no error, only line by line
debug
. - It was approved in a few hours.
- Lodash doesn’t support it. They said they had to fix something, but they didn’t tinker.
- Git also configured, really convenient, again sigh, but the syntax is really… Don’t want to use.
Afterword.
I don’t know how many versions I can do, but follow the practice, empty update. Set a flag and write a list haha.
- v1.0
- Challenge Invitation page
- v2.0
- Lose weight
- Social rewards
- Encouragement statement after check-in
- Wechat photo sharing
- v3.0
- list
- Good habits
- hierarchy
Code word code hand acid, for their own fuel.
Warehouse address: github.com/nihaojob/21…