Preface: In 2020, now small programs, though not of the most popular period, but little program “within reach, finished with the” concept for unknown developers to maintain a certain mystery and appeal, should the back-end students enthusiasm for small program development, the author during the period of the outbreak has developed and launched a small program “listen to read”, although is very simple, But with a little learning experience to share.

What is a applets

  • Like Web, but not HTML5
  • Cross-platform based on wechat
  • Comparable to native operating experience (voice, camera, geolocation…)
  • Connect wechat ecosystem (user information, socializing, wechat pay…)

You can scan the qr code above (you can also search for “mini program example”) to experience the functions of wechat mini program.

The development of preparation

Developers are required to have some front-end knowledge (HTML, CSS, JavaScript), “to do a good job, we must first use the tools”, we must first:

  • Download wechat developer tools,
  • Registering an AppID is a must in order for development to go live, although you can use a test number during development.

Todo-app demo

A front-end framework learning, are from todo-APP, small programs are the same

Create a project

After downloading, click select small program, first use, do not use the cloud service, click Finish, will help us initialize a simple small program project.

The directory structure

|- app.json
|- app.js
|- pages
   |- home
      |- home.wxml
      |- home.js
Copy the code

We see that the initialization code of the small program mainly includes JSON, JS, WXMl and WXCSS. WXMl corresponds to HTMl in the Web, and WXCSS corresponds to CSS in the Web.

Global configuration file

{
  "pages": ["pages/index/index"."pages/logs/index"]."window": {
    "navigationBarTitleText": "Demo"
  },
  "tabBar": {
    "list": [{"pagePath": "pages/index/index"."text": "Home page"
      },
      {
        "pagePath": "pages/logs/index"."text": "Log"}},"networkTimeout": {
    "request": 10000."downloadFile": 10000
  },
  "debug": true."navigateToMiniProgramAppIdList": ["wxe5f52902cf4de896"]}Copy the code

The app.json file in the root directory of the applets is used for global configuration of wechat applets, determining the path of page files, window performance, setting network timeout, setting multiple tabs, etc.

Configuration page

{
  "navigationBarBackgroundColor": "#ffffff"."navigationBarTextStyle": "black"."navigationBarTitleText": "Todo"."backgroundColor": "#eeeeee"."backgroundTextStyle": "light"
}
Copy the code

Each applet page can also use a.json file of the same name to configure the window representation of the page, and the configuration items in the page will override the same configuration items in the window of app.json.

wx.setNavigationBarTitle({
  title: 'Current page',})Copy the code

Of course, for dynamic pages, we can also change the title using the interface provided by WX

WXML view file

View WXML files are similar to HTML files used to build the page structure of the applet, unlike HTML:

  1. Instead of div, P and other block-level elements, they are replaced with view, scroll view tags

  2. Instead of span em A and other inline element tags, they are replaced with corresponding text and Navicator tags

  3. Provides abundant component labels modal, picker, swiper, etc., equivalent to the introduction of a component library.

WXSS style file

WXSS style files are equivalent to CSS files, but there are some differences:

  1. There are fewer selector types, only the ones shown above, no adjacent and attribute selectors, and fewer pseudo-class selectors (last-Child, etc.)

  2. New unit RPX. RPX is a 750px adaptive unit of the design document, that is, you define as many RPX as you measure on the 750px design document. On different devices, the small program can adapt.

The life cycle

Page life cycle

Page({
  data: {
    text: 'This is page data.',},onLoad: function (options) {
    // execute when the page is created
  },
  onShow: function () {
    // execute when the page appears in the foreground
  },
  onReady: function () {
    // execute when the page is first rendered
  },
  onHide: function () {
    // execute when the page changes from foreground to background
  },
  onUnload: function () {
    // execute when the page is destroyed
  },
  onPullDownRefresh: function () {
    // Execute when a pull-down refresh is triggered
  },
  onReachBottom: function () {
    // execute when the page hits the bottom
  },
  onShareAppMessage: function () {
    // execute when the page is shared by the user
  },
  onPageScroll: function () {
    // execute while the page is scrolling
  },
  onResize: function () {
    // execute when the page size changes
  },
  onTabItemTap(item) {
    // execute when TAB is clicked
    console.log(item.index)
    console.log(item.pagePath)
    console.log(item.text)
  },
  // The event response function
  viewTap: function () {
    this.setData(
      {
        text: 'Set some data for updating view.',},function () {
        // this is setData callback})},// Free data
  customData: {
    hi: 'MINA',}})Copy the code

Component life cycle

Component({

  behaviors: [].properties: {
    myProperty: { / / the property name
      type: String.value: ' '
    },
    myProperty2: String // A simplified definition
  },

  data: {}, // Private data that can be used for template rendering

  lifetimes: {
    // The lifecycle function can be a function, or a method name defined in the Methods section
    attached: function () {},moved: function () {},detached: function () {},},// The lifecycle function can be a function, or a method name defined in the Methods section
  attached: function () {},// The attached declaration here is overridden by the declaration in the LifeTimes field
  ready: function() {},pageLifetimes: {
    // The lifecycle function of the page on which the component is located
    show: function () {},hide: function () {},resize: function () {},},methods: {}}Copy the code

Like React and Vue, applets have their own life cycle functions, but the page life cycle of applets is different from the component life cycle. We don’t need to remember the life cycle functions above. When creating a new page using the developer tools, the tools automatically create the simplest page for us. When the mouse moves over the lifecycle function, the tool gives us a hint about what the function does.

event

<view id="tapTest" data-hi="Weixin" bindtap="tapName"> Click me! </view>
Copy the code
Page({
  tapName: function (event) {
    console.log(event)
  },
})
Copy the code
{
  "type": "tap"."timeStamp": 895."target": {
    "id": "tapTest"."dataset": {
      "hi": "Weixin"}},"currentTarget": {
    "id": "tapTest"."dataset": {
      "hi": "Weixin"}},"detail": {
    "x": 53."y": 14}}Copy the code

Events can be bound to methods on the page using instructions beginning with bind, or they can be bound to events using catch in addition to bind. Unlike bind, catch prevents events from bubbling up, and other categories of events can be viewed in the official documentation

Applets login

One of the biggest advantages of using small program development is that you can make use of wechat user system. We don’t need to do the functions of registration and login alone. We have an OpenID for all users through the small program to establish our own user system. If your small program is authenticated, you can obtain the mobile phone number bound to wechat users through getPhoneNumber.

Small program code, after login send res.code to the background for openId, sessionKey, unionId

onLaunch: function () {
   / /...
   wx.login({
      success: res= > {
         wx.request({
            url: 'https://next-5g925nky83ece5ae.service.tcloudbase.com/koa-starter/login'.method: 'POST'.data: {
               "JSCODE": res.code
            },
            success: (res) = > {
               const openid=res.data.openid
               this.globalData.openid=openid
            }
         })
      }
   })
   / /...
}
Copy the code

Back-end nodeJS code, according to the code to get the OpenID

router.post('/login'.async (ctx, next) => {
  const { JSCODE } = ctx.request.body
  const res = await axios.get('https://api.weixin.qq.com/sns/jscode2session', {
    params: {
      appid: AppID,
      secret: AppSecret,
      js_code: JSCODE,
      grant_type: 'authorization_code',
    },
  })

  ctx.body = res.data
})
Copy the code

Store openID in globalData for later calls

Write toDO code

The specific code, you can see the code warehouse, very simple, after each operation through the interface request, the data synchronization to the cloud. When traversing toDOS, we can wrap the Todo-Item into a custom component. Note that:

  • Because WXML node label names can only be lowercase letters, hyphens, and underscores, custom component label names can only contain these characters.

  • Custom components can also refer to custom components in a manner similar to how pages refer to custom components (using the usingComponents field).

  • The name of the root directory where custom components and pages reside cannot be prefixed with wx-; otherwise, an error message will be reported.

  • ID selectors, attribute selectors, and tag name selectors should not be used in component WXSS.

Development of cloud

You can see the URL interface requested above. From the domain name, I use Tencent Cloud Cloudbase. Cloudbase provides developers with high availability, automatic elastic expansion of back-end cloud services, including computing, storage, hosting and other serverless capabilities.

Actually just created the project, we can choose cloud development, WeChat will help us to automatically create a small program tencent cloud CloudBase account, also can use the function of cloud, the cloud database related functions such as, but WeChat developers provide cloud development function only support WeChat, web side does not support (now seemed to support the), My side will directly use Tencent cloud, convenient management

Nodejs Cloud function blank template

Let’s create a cloud function and CloudBase generates the following code for us

'use strict'
exports.main = async (event, context) => {
  console.log('Hello World')
  console.log(event)
  console.log(event['non-exist'])
  console.log(context)
  return event
}
Copy the code

Associate cloud functions with HTTP access services

After accessing the Http service, we can see Http request headers and other information. Combined with the cloud database, we can write the toDOs-related add, delete, check and change interface

Cloud development CloudBase Framework

We are used to using NodJS frameworks such as Express and KOA to develop interfaces. If we have to write all the interfaces separately, we will definitely feel a little uncomfortable. Don’t worry, Tencent Cloud CloudBase-Framework provides the ability to migrate and deploy traditional frameworks to cloud development. I believe that you only need to be familiar with the official project example, development and deployment.

The development of diverse

  • Wechat small program development completed — “tired”

  • What if I want to support other platforms? — “I can’t learn anymore.”

(H5, native APP, Alipay, Dingding, Baidu…)

Multi-terminal development framework

  • Taro, jingdong cave lab produced, official website address, using react and Vue development, cross-end support
  • Uni-app, produced by DCloud team, official website address, developed using VUE, cross-supported
  • Kbone, produced by Tencent wechat team, uses react and Vue to develop the official website address, but only supports web and wechat small programs
  • Remax, produced by Ali team, official website address developed by React, cross-supported

We can take a look at yesterday’s review article and follow the demo to learn about the next cross-end implementation. Uni – APP Author assessment address taro author assessment address

Taro2 implementation principle

Those of you who have experience developing the Babel plug-in should be familiar with the following process, which Taro followed when compilingbabel-parserParse the Taro code into an abstract syntax tree and passbabel-typesThe abstract syntax tree is modified, transformed, and finally passedbabel-generateGenerate the corresponding object code.

Taro2 characteristics

  • Recompile, run light: this can be seen by comparing the lines of code on both sides
  • Compiled code has nothing to do with React: Taro simply follows the React syntax while developing.
  • Compile directly with Babel: This also leads to Taro’s current weakness in engineering and plugins.

Implementation principle of Remax

React allows you to write small programs and native applications

The runtime essence of Remax is a small procedural renderer implemented through the React-Reconciler

Further reading

  • React Renderer Development Tutorial
  • Exploration and Practice of Small Program Cross-framework Development
  • Remax Implementation Principles

Summary and reflection

  • There is still a long way to go from the real production environment: we started to use cloud development to develop a Todo App wechat applet, but this is just a Hello World, applet also has functions such as payment and associated public account, only when these functions are developed, can the advantages of applet be realized.

  • Cross-end development is not difficult: we understand the cross-end development framework, and familiar with its implementation principle, from the developer’s point of view, we need to develop wechat Alipay and other small programs; From a browser perspective, however, the differences are not that great, as they all call the BOM/DOM API. From the React point of view, we only need to implement a rendering layer, not to mention that we can now use off-the-shelf frameworks for development.

Code warehouse

ppt.pdf

Thank you for reading, if reprinted, please note the source: running pony’s blog maqib.cn/post/1013