Summary of personal WeChat applet cloud development experience

Before article:

Attached are two small programs developed through WeChat Mini Program Cloud. Interested friends can scan the QR code on WeChat to have a look. Welcome to log in to learn Insert image description here
.

The framework adopts the commonly used UI on mobile terminals: Vant
WeChat cloud development official document: WeChat development document.
For related npm package import methods, you can read a previous blog post: How WeChat applet uses pubsub-js to achieve real-time communication between components and how to build the Vant framework> >Detailed explanation

1. Basic concepts of WeChat cloud development

Insert image description here


Official:
WeChat Cloud Development is a professional small program development service launched by the WeChat team and Tencent Cloud.
Developers can use cloud development to quickly develop mini programs, mini games, official account web pages, etc., and natively open up WeChat's open capabilities.
Developers do not need to build a server and can directly use the API provided by the platform for business development without authentication.


During development, I mainly used three basic cloud development capabilities of cloud development (database, cloud function, storage):
1. Cloud database
is a JSON database, which is simpler for a front-end to operate data than SQL. As long as you have some front-end basics, you can understand this kind of data.
2. Cloud functions.
The writing method of cloud functions is the same as writing nodejs, except that some related built-in methods of calling are different. I believe that writing cloud functions according to the official documents will be useful for most front-end users. It should be relaxing and enjoyable.

Simple example:

// 云函数入口文件
const cloud = require('wx-server-sdk') //导入云函数入口文件
cloud.init()
const db = cloud.database();//连接云数据库
// 云函数入口函数
exports.main = async (event, context) => {
    
    
//使用collection()方法发起请求,传入的是数据库集合名称,通过get()请求得到数据
 const {
    
    data} = await db.collection("login_duration").get()
 //当调用此云函数时,返回data数据
 return {
    
    
  data
 }
}

I would also like to add a sentence here. The default maximum number of requested data for cloud functions is 100, while the maximum number of requested data for mini programs is 20. 3.
Cloud storage
, as the name suggests, is a location for storing files, similar to a cloud disk, and quite On the server, the relevant files stored can be accessed through the corresponding links. I won’t go into details about this, it’s a very simple thing

2. Mini program/front end

Official Document: Basic Guide to WeChat Mini Programs

Personally, the main thing that needs to be remembered in the front-end position is the life cycle hook function of the page. In actual development, the WeChat applet will add the corresponding default life cycle function to our page JS by default and the basic data data that the page needs to use (modify For basic data data, we can directly use this.setData() method),
please see the example, this is the JS file automatically generated by the developer tool after we build the page in app.json (I have to say that it is very thoughtful , In addition, as the first JS file to be executed, there is a separate onLaunch() life cycle hook function in app.js , which is a function that will be executed when the user enters the mini program. It can be used to obtain the user's login time or initialization. request, etc.).

// pages/test/test.js
Page({
    
    

 /**
  * 页面的初始数据
  */
 data: {
    
    

 },

 /**
  * 生命周期函数--监听页面加载
  */
 onLoad(options) {
    
    

 },

 /**
  * 生命周期函数--监听页面初次渲染完成
  */
 onReady() {
    
    

 },

 /**
  * 生命周期函数--监听页面显示
  */
 onShow() {
    
    

 },

 /**
  * 生命周期函数--监听页面隐藏
  */
 onHide() {
    
    

 },

 /**
  * 生命周期函数--监听页面卸载
  */
 onUnload() {
    
    

 },

 /**
  * 页面相关事件处理函数--监听用户下拉动作
  */
 onPullDownRefresh() {
    
    

 },

 /**
  * 页面上拉触底事件的处理函数
  */
 onReachBottom() {
    
    

 },

 /**
  * 用户点击右上角分享
  */
 onShareAppMessage() {
    
    

 }
})

The other is the json file in the page. This file is generally not very useful unless there are related components or methods that need to be used separately on your current page. There is also a wxml file, which is equivalent to our HTML file, but there are also The difference is that we can fill in this file with the data corresponding to the data in JS to make the data "move" (this.setData() modifies the data data) using double curly
brackets (interpolation expression) { { }} Fill in the corresponding variables. When necessary, you can also fill in some basic JS syntax, which is usually simple syntax such as ternary expressions.
Insert image description here

3. Mini program/cloud function addition, deletion, modification and query database

The methods of adding, deleting, modifying, and checking are written in the same way on both the mini program and the cloud function. The only difference is the way of initializing cloud development. The applet is direct wx.cloud.init(), while the cloud function const cloud = require('wx-server-sdk') ;cloud.init()has an additional import method as mentioned before. In addition, it should be noted that the upper limit of database data obtained by the mini program and the cloud function is different (20 items for the mini program and 100 items for the cloud function, and the data returned at a time cannot be greater than 1M)

1. Mini program database addition, deletion, modification, query and front-end paging display

Official documents:
1. Add, delete, modify and check initialization
2. Related APIs
3. Related operators

The following is just a brief introduction to the APIs I used during the development process. For more details, please go to the official document 2 (related APIs) above. You are also welcome to leave a message in the comment area for everyone to learn and make progress together.

Add key method: add(data:{})
Please see the example:

const db = wx.cloud.database()
db.collection("login").add({
    
    
                  data: {
    
    data:"新增一条数据"}
               })

Delete key method: remove(),
please see the example:

const db = wx.cloud.database()
const _ = db.command()
//删除时一般都需要构造删除条件,where中传入的对象就是一个删除条件
db.collection("login").where({
    
    
                     _id: _.eq(id),
                     _openid
                  }).remove()

Change the key method: update(data:{})
, please see the example:

const db = wx.cloud.database()
db.collection("login").where({
    
    _id: _.eq(id)}.update({
    
    
                  data: {
    
    data:"修改一条数据"}
               })

Check Key methods: There are many query methods for where({})
. The following example only shows the simplest method. For various ways to build queries, it is recommended to refer to the official documentation: Building query conditions
. Please see the example:

const db = wx.cloud.database()
const _ = db.command()
db.collection("community").where({
    
    
            _id: _.eq(id),
         }).get().then(res =>{
    
    
      console.log(res.data)
      }).catch(err =>{
    
    
      console.log(err)}
      )

Paging key method: skip(index) / limit(number)
The database paging acquisition method mainly uses skip. This method passes in the index number and returns the data from the index number onward (20 items in the mini program, 100 in the cloud function) bar); limit() is used to return the required amount of data, passing in a value, which is used to control the amount of returned data. The range and scenarios used are much smaller than skip().
Similarly, you can also use where() to build query conditions before them.
Please see the example:

const db = wx.cloud.database()
//从数据库中第十条开始查询,只需要返回5条数据
db.collection("login").skip(10).limit(5).get().then(res =>{
    
    
	console.log(res.data);
}).catch(err =>{
    
    
console.log(err)
})

2. Add, delete, modify and query cloud function database

Cloud Function's basic ability to add, delete, modify, and query the database is the same. The difference is that the Cloud Function side has greater permissions, can modify other users' information, and has different cloud development initialization. Because it is almost the same as the mini program, here is only an example of deletion . Please test the others yourself.

  • Cloud function
//云函数名称为新建Node.js云函数时的名称
//此处测试名称为:remove
// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database();
// 云函数入口函数
exports.main = (event, context) => {
    
    
   try {
    
    
      db.collection("community").where({
    
    
         _id:event._id
      }).remove(res=>{
    
    
         result = res.errMsg
      }) 
      return true     
   } catch (err) {
    
    
      console.log(err)
      return false
   }
}
  • Calling cloud functions on the applet
let _id = e.target.dataset.id
wx.cloud.callFunction({
    
    
   name: "remove", //云函数名称,名称千万不能错,不然调用无效
   data: {
    
     _id },
   success: (res) => {
    
    
      console.log('remove success');
      console.log(res);
    },
  fail: (err) => {
    
    
     console.log('remove fail');
     console.log(err);
   }
})

4. Other points that need attention

  1. The addition, deletion, modification and query on the mini program can only be applied to individual users. What does this mean? For example, everyone should understand: If I, as an administrator, want to delete a user in the mini program, when deleting the user, I need to use the user's _openid (the unique id of each user in the mini program, Equivalent to the ID number in real life), but in the mini program, you can only obtain and use your own personal _openid, so this use requires the use of cloud functions to do the corresponding operations. This is the addition, deletion and modification of the database using the mini program. There is one thing you need to pay attention to when checking additions, deletions, and modifications on the cloud function side.
  2. The default and maximum upper limit of limit () on the mini program is 20, and the default and maximum upper limit on the cloud function is 1000.
  3. Some people need to visualize the backend database. At this time, you can consider using CMS content management. The entry method is: WeChat Developer Tools > Cloud Development > More > Content Management . Activate the backend visual database management on the content management page, through In this way, you can directly obtain a backend management system, through which users can directly add, delete, modify and check the database. It is very
    suitable for non-developers. The usage scenario is small programs developed by customers. Customers need to personally add, delete, and modify the database. check.
    Insert image description here

at last

This summary is at this point for the time being, and will continue to be updated during the later learning process. Thank you for watching. If there is any lack of support, please criticize and correct me, I will be grateful.

I hope this blog post can be helpful to you in developing WeChat mini programs.

Guess you like

Origin blog.csdn.net/weixin_51033461/article/details/125278746