Small Program Cloud Development Practical-Weight Recording Small Program

The small procedure just submitted has been approved and the notes are sent out. The previous paragraph saw that people in the circle of friends always use txt to record weight, so I especially wanted to write a small program to record weight. Now the cloud development of small programs has cloud functions and databases, which is really good for personal developers. Server domain names are not concerned about anything. Cloud development makes you completely free from these things.

Let's first look at the page renderings.







Several points recorded:

1. Global variable globalData

2. Use of NPM

3. Cloud function

4. Database operation

5. Use of Async

6. Sharing Configuration

7.antV usage

8.tabBar address jump

9. Switching Page Refresh

1. Global variable globalData

After the first entry, open Id is stored for other pages and shared with globalData.

<!--app.js Set up 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 examples
app.globalData.openid // Direct reference is enough.

2. Use of NPM

1. Enter the miniprogram directory of the applet source code and create the package.json file (use npm init to return all the way)

2.npm i --save the npm package we want to install

3. Setting up the developer tool of Wechat to build npm

4.package.json adds "miniprogram": "dist" to package directory fields. If not set, upload and preview are unsuccessful, indicating that the file package is too large.

cd miniprogram
npm init 
npm i @antv/f2-canvas --save   // I used f2, which I could replace with other packages.

Setting up Wechat Developer Tools

Constructing npm

Finally, be sure to add the miniprogram field

{
  "name": "21Day",
  "version": "1.1.0",
  "miniprogram": "dist",
  "description": "A 21-day weight record app",
  "license": "MIT",
  "dependencies": {
    "@antv/f2-canvas": "~1.0.5",
    "@antv/wx-f2": "~1.1.4"
  },
  "devDependencies": {}
}

3. Cloud function

Officially, cloud functions are functions that run in the cloud (server side). The server side is node.js. They are all JavaScript. Official database operations, but update operations mandatory use of cloud functions, in addition, if the cloud function uses npm package, remember to upload and deploy in the cloud function folder right-click, otherwise the operation failed.

For the last example, update the cloud function of body weight

// 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 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)
  }
}

Widget-side call

wx.cloud.callFunction({
     name: 'add',
     data: {
      ...Param
     },
     success: res => {
        wx.showToast({
          title: 'New Records Successful',
        })
     },
     fail: err => { 
        wx.showToast({
          icon: 'none',
          title: 'Failure to add new records'
        })
     }
   })

4. Database operation

In fact, MongoDB is accessed. It encapsulates a part of the api. Look at it in detail. Official Documents Well, there are differentiated servers and small program segments.

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
    }
})

5. Use of Async

Official documentation hints that async is not supported and the package regenerator Runtime needs to be introduced, first npm i regenerator.
Then copy the runtime-module.js and runtime.js files of regenerator-runtime under the node_modules folder into the lib directory and introduce them into the page.

<!--Example-->
const regeneratorRuntime = require('../../lib/runtime.js')
onLoad: async function (options) {

    // Get the day's data
    await this.step1()

    // Time Type Settings
    let nowHour = moment().hour(),timeType
    nowHour > 12 ? timeType = 'evening' : timeType = 'morning'
    this.setData({timeType})
  }

6. Sharing Configuration

Sharing is simple. There is a distinction between direct sharing in the upper right corner and button-clicking sharing.

onShareAppMessage: function (res) {
        
      // Share in the upper right corner
      let ShareOption = {
        title: '21 Daily Weight Loss Record',
        path: '/pages/index/index',
      } 
      
      // Button Sharing
      if(res.from == "button"){
        ShareOption = {
            title: 'Come on, look at my weight loss record.',
            path: '/pages/detail/detail?item=' + app.globalData.openid,
          } 
      }
      
      return ShareOption
  }

After sharing, others click on the page, jump to the corresponding pages address, and take the number of requests from onLoad's options.

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
        })

      }
    })
  },

7.antV usage

The installation of antV is mentioned in the second section above, so let's not go into it any more. Let's talk about it directly and then refer to it on the page.

To use this, you need to set up a global variable to store an instance of the graph, and then use the changeData method to modify the data in the hook function content.

Introduction of package names in index.json

{
  "usingComponents": {
      "ff-canvas": "@antv/f2-canvas"
  }
}
// Introduction of F2
import F2 from '@antv/wx-f2';

// Setting instance global variables (be sure)
let chart = null;
function initChart(canvas, width, height, F2) { // Drawing Charts Using F2
  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';
      }
      return textCfg;
    }
  });

  chart.axis('step', {
    label(text) {
      return {
        text: text / 1000 + 'k step'
      };
    }
  });

  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(0) 0:#F2C587 0.5:#ED7973 1:#8659AF');
  chart.line().position('timestamp*step').shape('smooth').color('l(0) 0:#F2C587 0.5:#ED7973 1:#8659AF');
  chart.render();
  return chart;
}

// Life cycle function
onLoad(){
    // Using changeData to assign values
    chart.changeData(stepInfoList)
}

8.tabBar address jump

If the address you want to jump is not in the tabBar of app.json, you can use wx.navigateTo. If you can't jump, you can use wx.switchTab method to jump.

wx.switchTab({
  url: '/pages/add/add',
  fail: function(e) {}
})

wx.navigateTo({
  url: '../deployFunctions/deployFunctions',
})

9. Switching Page Refresh

When switching several tabBar s, you need to refresh the data. Call the onLoad method again in the onShow method.

onShow: function () {
    this.onLoad()
}

Source Link

https://github.com/TencentClo...

If you want to share your technical stories / experiences in developing CloudBase using the cloud, please leave a message to contact us.

Keywords: Python npm Database JSON Javascript

Added by CBaZ on Mon, 05 Aug 2019 11:32:59 +0300