Basic process of wechat applet development

1, Introduction to wechat applet

1. Wechat applet is called applet for short. The applet released by Zhang Xiaolong on wechat open class Pro was officially launched on January 9, 2017.

2. The word wechat applet can be divided into "wechat" and "applet"

(1) Among them, "wechat" can be understood as "in wechat", which refers to the execution environment of small programs; Of course, while providing the execution environment, wechat also prolongs the time for users to use wechat.

(2) "Applet" means that it is a program first, and then has the characteristics of portability. Unlike other applications, small programs do not need to be installed, but are opened and executed directly by scanning QR codes; There is no need to uninstall after use. This is the so-called "run out and go" principle.

3. For wechat applets, many similar applications adopt similar architectures:

  • JSON technology is used to represent the configuration information of the application. It includes the basic information of the application, page configuration and routing, information of the whole application, etc.

  • Use customized CSS+XML technology to realize the description of view layer. Screen elements, such as lists, buttons, text boxes, selection boxes, etc., are described in XML language, follow XML syntax, and use CSS to define the common style of the page.

  • Use JavaScript language to implement the logical layer structure. Including user operation processing, system API call, etc.

  • The architecture provides data and event transmission between the view layer and the logic layer, so as to minimize the difficulty. Since similar applications belong to light applications, the functions provided are relatively single.

4. JSON (JavaScript Object Notation) is a lightweight data exchange format. It is based on a subset of ECMAScript (JavaScript specification formulated by W3C) and uses a text format completely independent of the programming language to store and represent data. The concise and clear hierarchy makes JSON an ideal data exchange language. It is easy for people to read and write, but also easy for machine analysis and generation, and effectively improves the network transmission efficiency.

5. XML (Extensible Markup Language), called extensible markup language in Chinese, is a subset of the standard general markup language. It is a markup language used to mark electronic documents to make them structured.

In electronic computers, marks refer to information symbols that can be understood by computers. Through this mark, computers can process various information, such as articles, etc. It can be used to mark data and define data types. It is a source language that allows users to define their own markup language. It is very suitable for world wide web transmission and provides a unified method to describe and exchange structured data independent of applications or suppliers. It is a cross platform and content dependent technology in the Internet environment. It is also an effective tool to deal with distributed structure information. As early as 1998, W3C released the XML 1.0 specification to simplify the document information transmission on the Internet.

6. CSS Cascading Style Sheets (English full name: Cascading Style Sheets) is a computer language used to represent file styles such as HTML or XML. CSS can not only modify the web page statically, but also format the elements of the web page dynamically with various scripting languages. CSS can accurately control the layout of elements in the web page at the pixel level, support almost all font and size styles, and have the ability to edit web page objects and model styles.

7. JavaScript is a literal script language. It is a dynamic type, weak type, prototype based language with built-in support of types. Its interpreter is called JavaScript engine, which is a part of the browser. It is widely used in client scripting language. It was first used on HTML web pages to add dynamic functions to HTML web pages.
 

2, Register wechat applet

Before creating your own wechat applet, you need to Register applet account There are the following account types:

For the specific registration process, please refer to the official API Tutorial

3, Installing tools, creating projects

Step 1: Download and install the wechat applet developer tool. Download path:

 Stable Build | wechat open document

After entering the download interface, select the corresponding link to download according to your own operating system, and install after downloading.

Step 2: install the login tool

After the developer tool is installed, we can open it. For the first time, we need to log in with wechat scanning code, as shown in the figure below. After scanning with mobile wechat, we can confirm the login.

Step 3: select an item type

After successful login, if this tool is used for the first time, a window for selecting item type will pop up, as shown in the following figure:

Step 4: create a project

After selecting the item type successfully, the create item window will pop up, as shown in the following figure:

During the creation process, if the selected local folder is an empty folder, a check box "build cloud development quick start template" will appear. In order to facilitate beginners to understand the basic code structure of wechat applet, please check this box. After checking this box, the developer tool will help us generate a simple demo in the development directory, as shown in the following figure:

4, Description and development of project code structure

4.1 project code structure

Click the "editor" on the upper navigation of the developer tool. We can 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. The. JS suffix is the script file, the. JSON suffix is the configuration file, and the. Wxss suffix is the style sheet file. Wechat applet will read these files and generate applet instances.

Let's briefly understand the functions of these three files to facilitate modification and develop our own wechat applet from scratch.

1. app.js is the script code of the applet. In this file, we can listen to and process the life cycle function of the applet and declare global variables. Call the rich API s provided by the framework, such as synchronous storage and synchronous reading of local data in this example.

2. app.json is the global configuration of the entire applet. In this file, we can configure which pages the applet is composed of, configure the window background color of the applet, configure the navigation bar style, and configure the default title. Note that no comments can be added to this file.

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

We notice that there are two folders in the code of the example program, one is pages and the other is style, where style is a folder for general styles and pages is a folder for storing all pages. Let's focus on the pages

4.2 composition of applet page file

In this example, we have seven pages, the index page, that is, the welcome page, which are all in the pages directory. The [path + page name] of each page in the wechat applet needs to be written in the pages of app.json, and the first page in the pages is the front page of the applet.

  Each applet page is composed of four different suffix files with the same name under the same path, such as index.js, index.wxml, index.wxss and index.json JS suffix files are script files,. JSON suffix files are configuration files,. Wxss suffix files are style sheet files, and. Wxml suffix files are page structure files.

index.wxml is the structure file of the page:

<!--index.wxml-->
<view class="container">

  <!-- user openid -->
  <view class="userinfo">
    <button
      open-type="getUserInfo"
      bindgetuserinfo="onGetUserInfo"
      class="userinfo-avatar"
      style="background-image: url({{avatarUrl}})"
    ></button>
    <view>
      <text>jackson Yingqi</text>
</view>
</view>

<view class="text-title">
      <text>Hello world</text>
</view>
</view>
 

In this example, the <view/>,<button/>,<text/> To build page structure, bind data and interactive processing functions.

index.js is the script file of the page. In this file, we can listen to and process the life cycle function of the page, obtain the applet instance, declare and process data, respond to page interaction events, etc.

//index.js
const app = getApp()

Page({
  data: {
    avatarUrl: './user-unlogin.png',
    userInfo: {},
    logged: false,
    takeSession: false,
    requestResult: ''
  },

  onLoad: function() {
    if (!wx.cloud) {
      wx.redirectTo({
        url: '../chooseLib/chooseLib',
      })
      return
    }

    // Get user information
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // Authorized, you can directly call getUserInfo to get the avatar nickname without popping the box
          wx.getUserInfo({
            success: res => {
              this.setData({
                avatarUrl: res.userInfo.avatarUrl,
                userInfo: res.userInfo
              })
            }
          })
        }
      }
    })
  },

  onGetUserInfo: function(e) {
    if (!this.logged && e.detail.userInfo) {
      this.setData({
        logged: true,
        avatarUrl: e.detail.userInfo.avatarUrl,
        userInfo: e.detail.userInfo
      })
    }
  },

  onGetOpenid: function() {
    // Call cloud function
    wx.cloud.callFunction({
      name: 'login',
      data: {},
      success: res => {
        console.log('[Cloud function] [login] user openid: ', res.result.openid)
        app.globalData.openid = res.result.openid
        wx.navigateTo({
          url: '../userConsole/userConsole',
        })
      },
      fail: err => {
        console.error('[Cloud function] [login] Call failed', err)
        wx.navigateTo({
          url: '../deployFunctions/deployFunctions',
        })
      }
    })
  },

  // Upload pictures
  doUpload: function () {
    // Select Picture
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {

        wx.showLoading({
          title: 'Uploading',
        })

        const filePath = res.tempFilePaths[0]

        // Upload pictures
        const cloudPath = 'my-image' + filePath.match(/\.[^.]+?$/)[0]
        wx.cloud.uploadFile({
          cloudPath,
          filePath,
          success: res => {
            console.log('[Upload file] success:', res)

            app.globalData.fileID = res.fileID
            app.globalData.cloudPath = cloudPath
            app.globalData.imagePath = filePath

            wx.navigateTo({
              url: '../storageConsole/storageConsole'
            })
          },
          fail: e => {
            console.error('[Upload file] Failed:', e)
            wx.showToast({
              icon: 'none',
              title: 'Upload failed',
            })
          },
          complete: () => {
            wx.hideLoading()
          }
        })

      },
      fail: e => {
        console.error(e)
      }
    })
  },

})
  

index.wxss is the style sheet of the page:

/**index.wxss**/

page {
  background: #f6f6f6;
  display: flex;
  flex-direction: column;
  justify-content: center;
}
.userinfo, .uploader, .tunnel {
  margin-top: 40rpx;
  height: 140rpx;
  width: 100%;
  background: #fff;
  border: 1px solid rgba(0, 0, 0, 0.1);
  border-left: none;
  border-right: none;
  display: flex;
  flex-direction: row;
  align-items: center;
  transition: all 300ms ease;
}

.userinfo-avatar {
  width: 100rpx;
  height: 100rpx;
  margin: 20rpx;
  border-radius: 50%;
  background-size: cover;
  background-color: white;
}

.userinfo-avatar:after {
  border: none;
}

.userinfo-nickname {
  font-size: 32rpx;
  color: #007aff;
  background-color: white;
  background-size: cover;
}

.userinfo-nickname::after {
  border: none;
}

.uploader, .tunnel {
  height: auto;
  padding: 0 0 0 40rpx;
  flex-direction: column;
  align-items: flex-start;
  box-sizing: border-box;
}

.uploader-text, .tunnel-text {
  width: 100%;
  line-height: 52px;
  font-size: 34rpx;
  color: #007aff;
}

.uploader-container {
  width: 100%;
  height: 400rpx;
  padding: 20rpx 20rpx 20rpx 0;
  display: flex;
  align-content: center;
  justify-content: center;
  box-sizing: border-box;
  border-top: 1px solid rgba(0, 0, 0, 0.1);
}

.uploader-image {
  width: 100%;
  height: 360rpx;
}

.tunnel {
  padding: 0 0 0 40rpx;
}

.tunnel-text {
  position: relative;
  color: #222;
  display: flex;
  flex-direction: row;
  align-content: center;
  justify-content: space-between;
  box-sizing: border-box;
  border-top: 1px solid rgba(0, 0, 0, 0.1);
}

.tunnel-text:first-child {
  border-top: none;
}

.tunnel-switch {
  position: absolute;
  right: 20rpx;
  top: -2rpx;
}

.disable {
  color: #888;
}

.service {
  position: fixed;
  right: 40rpx;
  bottom: 40rpx;
  width: 140rpx;
  height: 140rpx;
  border-radius: 50%;
  background: linear-gradient(#007aff, #0063ce);
  box-shadow: 0 5px 10px rgba(0, 0, 0, 0.3);
  display: flex;
  align-content: center;
  justify-content: center;
  transition: all 300ms ease;
}

.service-button {
  position: absolute;
  top: 40rpx;
}

.service:active {
  box-shadow: none;
}

.request-text {
  padding: 20rpx 0;
  font-size: 24rpx;
  line-height: 36rpx;
  word-break: break-all;
}
.text-title{
margin-top: 50%;
}
.text-title text{
  font-size: 96rpx;
  font-family: 'Franklin Gothic Medium', 'Arial Narrow', Arial, sans-serif;
}

  A style sheet for a page is not necessary. When there is a page style sheet, the style rules in the style sheet of the page will overlay the style rules in app.wxss. If you do not specify the style sheet of the page, you can also directly use the style rules specified in app.wxss in the structure file of the page.

index.json is the configuration file of the page:

The configuration file for the page is not necessary. When there is a configuration file for a page, the configuration item will overwrite the same configuration item in the window of app.json on this page. If there is no specified page configuration file, the default configuration in app.json is directly used on this page.

{
  "pages": [
    "pages/index/index",
    "pages/userConsole/userConsole",
    "pages/storageConsole/storageConsole",
    "pages/databaseGuide/databaseGuide",
    "pages/addFunction/addFunction",
    "pages/deployFunctions/deployFunctions",
    "pages/chooseLib/chooseLib"
  ],
  "window": {
    "backgroundColor": "#F6F6F6",
    "backgroundTextStyle": "light",
    "navigationBarBackgroundColor": "#F6F6F6",
    "navigationBarTitleText": "jackson Yingqi",
    "navigationBarTextStyle": "black"
  }
}

The operation results are as follows:

Mobile Preview

Click "Preview" in the menu bar on the upper side of the developer tool. After scanning the code, you can experience it in the wechat client.

Tags: Javascript Mini Program

Posted on Wed, 24 Nov 2021 17:48:37 -0500 by thirdeye