A Simple Course for the Development of Wechat Programs

1. Get the AppID of the Wechat applet (Note that the AppID here is a special id for the widget. You can see it in the widget public number widget, without some functions of the AppID will be limited!)

Login https://mp.weixin.qq.com In the "Settings" - "Developer Settings" of the website, you can see the AppID of the Wechat applet, and pay attention not to use the AppID of the service number or subscription number directly.

Note: If we want to experience the applet on a mobile phone with non-administrator micro-signals, then we need to operate "Binding Developer". That is, in the "user identity" - "developer" module, the binding needs to experience the micro-signal of the applet. By default, this tutorial registers accounts and experiences using administrator micro-signals.

2. Create a project (the name of the project is usually English, try not to use Chinese, may report errors)

We need to pass Developer Tools To complete widget creation and code editing.

After the developer tool is installed, open and log in using Wechat Scan Code. Select Create Item, fill in the AppID obtained above, set the name of a local project (non-widget name), such as "My first project", and select a local folder as the directory of code storage. Just click "New Project".

In order to facilitate beginners to understand the basic code structure of Wechat applet, if the local folder selected is an empty folder during the creation process, the developer tool will prompt whether a quick start project needs to be created. By choosing Yes, the developer tool will help us generate a simple demo in the development directory.

After successful project creation, we can click on the project, enter and see the complete developer tool interface, click on the left navigation, view and edit our code in the "edit", test the code in the "debug" and simulate the widget effect in the Wechat client, and send it to the mobile phone to preview the actual effect in the "project".

3. Write code (small programs have their own specific labels)

Create applet instances

Click "Edit" in the left navigation of the developer tool to see that the project has been initialized and contains some simple code files. The most critical and essential are app.js, app.json and app.wxss. Among them,.Js suffix is script file,.json suffix file is configuration file,.Wxss suffix is style sheet file. The Wechat applet reads these files and generates them. Instances of small programs.

Below we have a brief understanding of the functions of these three files, easy to modify and develop their own micro-messaging program from scratch.

app.js is the script code of the applet. In this file, we can monitor and process the life cycle functions of the applet and declare global variables. The invocation framework provides rich APIs, such as synchronous storage and synchronous reading of local data for this example. For more information on APIs available, refer to API documentation

//app.js
App({
  onLaunch: function () {
    //Call API to retrieve data from local cache
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)
  },
  getUserInfo:function(cb){
    var that = this;
    if(this.globalData.userInfo){
      typeof cb == "function" && cb(this.globalData.userInfo)
    }else{
      //Call login interface
      wx.login({
        success: function () {
          wx.getUserInfo({
            success: function (res) {
              that.globalData.userInfo = res.userInfo;
              typeof cb == "function" && cb(that.globalData.userInfo)
            }
          })
        }
      });
    }
  },
  globalData:{
    userInfo:null
  }
})

app.json is the global configuration of the entire applet. In this file, we can configure which pages the widget consists of, configure the window background color of the widget, configure the navigation bar style, and configure the default title. Note that no comments can be added to this file. More configurable items are available for reference Detailed configuration

{
  "pages":[
    "pages/index/index",
    "pages/logs/logs"
  ],
  "window":{
    "backgroundTextStyle":"light",
    "navigationBarBackgroundColor": "#fff",
    "navigationBarTitleText": "WeChat",
    "navigationBarTextStyle":"black"
  }
}

app.wxss is the common style sheet for the entire applet. We can use the style rules declared in app.wxss directly on the class attribute of the page component.

/**app.wxss**/
.container {
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-between;
  padding: 200rpx 0;
  box-sizing: border-box;
}

Create pages

In this tutorial, we have two pages, index page and logs page, which are welcome page and display page of applet startup log. They are all in pages directory. Every page in the Wechat applet program [path + page name] needs to be written in app.json pages, and the first page in pages is the home page of the applet.

Every last Applet page It consists of four different suffix files with the same name under the same path, such as index.js, index.wxml, index.wxss and index.json. The files with.Js suffix are script files, the files with.Json suffix are configuration files, the files with.Wxss suffix are style sheet files, and the files with.Wxml suffix are page structure files.

index.wxml is the structure file of the page:

<!--index.wxml-->
<view class="container">
  <view  bindtap="bindViewTap" class="userinfo">
    <image class="userinfo-avatar" src="{{userInfo.avatarUrl}}" background-size="cover"></image>
    <text class="userinfo-nickname">{{userInfo.nickName}}</text>
  </view>
  <view class="usermotto">
    <text class="user-motto">{{motto}}</text>
  </view>
</view>

This example uses the <view/>,<image/>,<text/> To build a page structure, binding data and interactive processing functions.

index.js is a script file of a page. In this file, we can monitor and process the life cycle function of the page, obtain small program instances, declare and process data, and respond to page interaction events.

//index.js
//Get application examples
var app = getApp()
Page({
  data: {
    motto: 'Hello World',
    userInfo: {}
  },
  //Event Handler
  bindViewTap: function() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  onLoad: function () {
    console.log('onLoad')
    var that = this
    //Call the method of application instance to get global data
    app.getUserInfo(function(userInfo){
      //Update data
      that.setData({
        userInfo:userInfo
      })
    })
  }
})

index.wxss is the stylesheet of the page:

/**index.wxss**/
.userinfo {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.userinfo-avatar {
  width: 128rpx;
  height: 128rpx;
  margin: 20rpx;
  border-radius: 50%;
}

.userinfo-nickname {
  color: #aaa;
}

.usermotto {
  margin-top: 200px;
}

The stylesheet of the page is not necessary. When there is a page style sheet, the style rules in the page style sheet overlay the style rules in app.wxss. If you don't specify a page's style sheet, you can also directly use the style rules specified in app.wxss in the page's structure file.

index.json is the configuration file for the page:

Configuration files for pages are not necessary. When there is a configuration file for a page, the same configuration item in app.json's window is overwritten by the configuration item on that page. If no page configuration file is specified, the default configuration in app.json is used directly on that page.

Page structure of logs

<!--logs.wxml-->
<view class="container log-list">
  <block wx:for="{{logs}}" wx:for-item="log">
    <text class="log-item">{{index + 1}}. {{log}}</text>
  </block>
</view>

logs page usage <block/> Control labels to organize code, using <block/>. wx:for Binding logs data and looping logs data to expand nodes

//logs.js
var util = require('../../utils/util.js')
Page({
  data: {
    logs: []
  },
  onLoad: function () {
    this.setData({
      logs: (wx.getStorageSync('logs') || []).map(function (log) {
        return util.formatTime(new Date(log))
      })
    })
  }
})

The results are as follows:

4. Mobile phone preview (joining developers or operators can generate two-dimensional code directly into the scanner!)

The left menu bar of the developer's tool chooses "Project" and clicks "Preview" to experience it in the Wechat client.

Keywords: Javascript JSON Mobile Attribute

Added by treybraid on Fri, 21 Jun 2019 04:34:48 +0300