The world's first WeChat application account development tutorial! I vomited blood all night to catch up with the draft, and it is updated every day! (Turn)

Original: https://my.oschina.net/wwnick/blog/750055

Learning materials: https://github.com/justjavac/awesome-wechat-weapp?hmsr=toutiao.io&utm_medium=toutiao.io&utm_source=toutiao.io#%E5%AE%98%E6%96%B9%E6%96% 87%E6%A1%A3

 

Preamble

Before starting to develop an app account, take a look at the official "Mini Program" tutorial! (The following content is from the "Mini Program" development guide officially announced by WeChat)

This document will take you step by step to create a WeChat applet, and you can experience the actual effect of the applet on your mobile phone. The homepage of this applet will display the welcome message and the WeChat avatar of the current user. Click on the avatar to view the startup log of the current applet on the newly opened page.

1. Get the AppID of the WeChat applet

First, we need to have an account, if you can see the document, we should have invited and created an account for you. Note that the AppID of the service account or subscription account cannot be used directly. Using the provided account, log  in to https://mp.weixin.qq.com  , and you can view the AppID of the WeChat applet in the website's "Settings" - "Developer Settings".

Note: If we do not use the administrator WeChat account bound during registration, experience the applet on the mobile phone. Then we also need to operate the "binding developer". That is, in the "User Identity - Developer" module, bind the WeChat account that needs to experience the applet. This tutorial uses the administrator's WeChat account by default for account registration and experience.

2. Create a project

We need to use developer tools to complete applet creation and code editing.

After the developer tool is installed, open it and use WeChat to scan the code to log in. Select Create "Project", fill in the AppID obtained above, set the name of a local project (not a small program name), such as "My First Project", and select a local folder as the code storage directory , and click New Project.

In order to facilitate beginners to understand the basic code structure of WeChat Mini Programs, during the creation process, if the selected local folder is an empty folder, the developer tool will prompt you whether you need to create a quick start project. Select "Yes", the developer tools will help us generate a simple demo in the development directory.

After the project is created successfully, we can click on the project to enter and see the complete developer tool interface, click on the left navigation, in "Edit", we can view and edit our code, in "Debug", we can test the code and Simulate the effect of the applet on the WeChat client, and in "Project", you can send it to the mobile phone to preview the actual effect.

3. Write the code

Click "Edit" in the left navigation of the developer tools, we can see that this project has been initialized and contains some simple code files. The most critical and essential ones are app.js, app.json, and app.wxss. Among them, the .js suffix is ​​the script file, the .json suffix is ​​the configuration file, and the .wxss suffix is ​​the style sheet file. The WeChat Mini Program will read these files and generate Mini Program instances.

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

app.js is the script code of the applet. We can monitor and process the applet's life cycle functions and declare global variables in this file. Call the rich API provided by MINA, such as synchronous storage and synchronous reading of local data in this example.

//app.js

App({

  onLaunch: function () {

    // 调用 API 从本地缓存中获取数据

    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{



      // 调用登录接口

      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 for the entire applet. In this file, we can configure which pages the applet consists of, configure the background color of the applet's window, configure the style of the navigation bar, and configure the default title. Note that no comments can be added to this file.

/**app.json*/
{

  "pages":[

    "pages/index/index",

    "pages/logs/logs"

  ],

  "window":{

    "backgroundTextStyle":"light",

    "navigationBarBackgroundColor": "#fff",

    "navigationBarTitleText": "WeChat",

    "navigationBarTextStyle":"black"

  }

}

app.wxss is the common stylesheet 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;

}

3. Create a page

In this tutorial, we have two pages, the index page and the logs page, namely the welcome page and the display page of the applet startup log, they are all under 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 pages is the home page of the applet.

Each applet page is composed of four files with different suffixes with the same name under the same path, such as index.js, index.wxml, index.wxss, and index.json. A file with a .js suffix is ​​a script file, a file with a .json suffix is ​​a configuration file, a file with a .wxss suffix is ​​a style sheet file, and a file with a .wxml suffix is ​​a page structure file.

index.wxml is the structure file of the page:

<!--index.wxml--><viewclass="container">

  <view  bindtap="bindViewTap"class="userinfo">

    <imageclass="userinfo-avatar"src="{{userInfo.avatarUrl}}"background-size="cover"></image>

    <textclass="userinfo-nickname">{{userInfo.nickName}}</text>

  </view>

  <viewclass="usermotto">

    <textclass="user-motto">{{motto}}</text>

  </view></view>

In this example, <view/>, <image/>, and <text/> are used to build the page structure, bind data and interact with processing functions.

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

//index.js

// 获取应用实例

var app = getApp()

Page({

  data: {

    motto: 'Hello World',

    userInfo: {}

  },

  // 事件处理函数

  bindViewTap: function() {

    wx.navigateTo({

      url: '../logs/logs'

    })

  },

  onLoad: function () {

    console.log('onLoad')

    var that = this

    // 调用应用实例的方法获取全局数据

    app.getUserInfo(function(userInfo){

      // 更新数据

      that.setData({

        userInfo:userInfo

      })

    })

  }

})

index.wxss is the stylesheet for 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 page's style sheet is not necessary. When there is a page style sheet, the style rules in the page's style sheet are cascaded to override the style rules in app.wxss. If you do not specify the style sheet of the page, you can also use the style rules specified in app.wxss directly in the structure file of the page.

index.json is the configuration file for the page:

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

The page structure of logs

<!--logs.wxml--><viewclass="container log-list">

  <blockwx:for-items="{{logs}}"wx:for-item="log">

    <textclass="log-item">{{index + 1}}. {{log}}</text>

  </block></view>

The logs page uses the <block/> control tag to organize the code, uses wx:for-items on the <block/> to bind the logs data, and expands the logs data loop to the node

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

On the left menu bar of the developer tool, select "Project", click "Preview", and you can experience it in the WeChat client after scanning the code.

At present, the preview and upload functions are not yet available, and we need to wait for the next official update of WeChat.

As you can see, the development guide given by WeChat official is still very simple, and many details, codes and functions are not clearly displayed, so it is time for Bokajun to show his strength! The development tutorial officially begins!

Chapter 1: Preparations

It's important to be prepared. To develop a WeChat application account, you need to download the developer tools from the WeChat official website (weixin.qq.com) in advance.

1. Download the latest WeChat Developer Tools, open it and you will see this interface:

2. Click the "New web+" item, and the following screen will appear:

3. The contents of this page need to be paid attention to—

  • AppID: Fill in according to the official explanation.
  • Appname: The name of the outermost folder of the project. If you name it "ABC", all subsequent project contents will be saved in the "/ABC/..." directory.
  • Local development directory: The directory where the project is stored locally.

Note: Again, if you and team members develop the project together, it is recommended that you use the same directory name and local directory to ensure the unity of collaborative development. If you have a project before, the import process is similar to the above, so I won't repeat it.

4. After all the preparations are completed, click the "New Project" button, and click "OK" in the pop-up box.

5. As shown in the figure above, at this moment, the WeChat developer tool has automatically built an initial demo project for you, which contains the basic content and framework structure required for a WeChat application project. Click on the project name (“cards” in the figure) to enter the project, and you can see the basic structure of the entire project:

Chapter 2: Project Architecture

At present, WeChat has a very large user base. After the launch of WeChat’s official account, everyone can see its popularity, which also promotes the rapid development of h5. With the increasingly complex needs of the official account business, the arrival of the application account is just right. After reading the document once or twice, our team found that the way it provides developers is also undergoing a comprehensive change, from manipulating DOM to manipulating data, based on a bridge tool provided by WeChat, it is difficult to implement a lot of h5 in the public account. The functions implemented are somewhat similar to hybrid development, but different from the hybrid development method: the open interface of WeChat is more rigorous, the structure must use the components provided to us, and external frameworks and plug-ins cannot be used here, allowing development The developer is completely out of the operation DOM, and the development thinking has changed a lot.

If a worker wants to do a good job, he must first sharpen his tools. It is very important to understand its core function, first understand its entire operation process.

The life cycle:

Inside index.js:

On the console of the developer tools, you can see:

On the home page console, you can see that the order is App Launch-->App Show-->onload-->onShow-->onReady.

The first is the startup and display of the entire app. The startup of the app can be configured in app.js, and then it goes to the loading display of each page and so on.

It is conceivable that many things can be handled here, such as loading boxes and the like can be implemented and so on.

routing:

Routing has always been a core point in project development. In fact, WeChat has very little introduction to routing here. It can be seen that WeChat has been well encapsulated in routing and also provides three jump methods.

wx.navigateTo(OBJECT): Keep the current page, jump to a page in the app, and use wx.navigateBack to return to the original page.

wx.redirectTo(OBJECT): Close the current page and jump to a page in the application.

wx.navigateBack(): Close the current page and go back to the previous page.

These three are basically enough, and WeChat encapsulates very well in terms of routing. Developers do not need to configure routing at all. Often, many frameworks are very cumbersome in routing configuration.

Components:

This time, WeChat is also very comprehensive in terms of component provision, which basically meets the needs of the project, so the development speed is very fast. You can carefully browse several times before development, and the development efficiency will be very good.

other:

Any external frameworks and plug-ins are basically unusable, and even native js plug-ins are difficult to use, because in the past our js plug-ins basically all existed in the form of a DOM operation, and the WeChat application account's architecture does not allow operation. Any dom, even the dynamically set rem.js that we used to use before, is not supported.

This time, WeChat also provides WebSocket, which can be directly used for chatting, and the development space is very large.

Compared with the official account, we found that the development application account is componentized, structured and diversified. The new continent is always full of surprises, and more easter eggs are waiting for you to discover.

Let's start with some simple code!

1. Find the project folder and import it into your editor. Here, I used the Sublime Text editor. You can choose your favorite editor according to your development habits.

2. Next, you need to adjust the project structure according to your own project content. In the example project, the "card_course" directory mainly contains the "tabBar" page and some configuration files of the application.

3. The "tabBar" of the example project is five menu buttons:

4. Find the "app.json" file to configure the five menus. Find ""tabBar"" in the line of code:

You can change it according to actual project needs, among which:

  • "Color" is the bottom font color, "selectedColor" is the highlight color of the page to switch to, "borderStyle" is the color of a line above the toggle menu, and "backgroundColor" is the background color of the bottom menu bar. The text description is relatively abstract. It is recommended that you debug and check its effects one by one to deepen your impression.
  • The order of codes under "list" must be placed in sequence and cannot be changed arbitrarily.
  • In the file name after ""pagePath"", the ".wxml" suffix is ​​hidden, which is a humanized point in WeChat development code - it helps you save the time of writing code, and you don't need to declare the file suffix frequently.
  • ""iconPath"" is the icon path of the undisplayed page, and these two paths can be directly network icons.
  • ""selectedIconPath"" is the highlighted icon path of the currently displayed page, which can be removed. After removal, the icon of ""iconPath"" will be displayed by default.
  • ""Text"" is the page title, which can also be removed. After removal, the icon will be displayed only. If only one of them is removed, the position will be occupied.

Note: The bottom menu of WeChat supports up to five columns (five icons), so when you design the UI and basic structure of the WeChat application, you should consider the layout of the menu bar in advance.

5. According to the above code rules, I have prepared the basic structure of the sample project for your reference:

6. After the "Json" file is configured, the basic structure of "card_course" is shown in the figure above. Unnecessary subsets can be temporarily deleted, and missing subsets need to be created on your own initiative. When deleting a subset, remember to check whether the relevant content in "app.json" has been deleted as well.

Note: I personally recommend that you create a new "wxml" file, and create the corresponding "js" and "wxss" files together, because the configuration feature of the WeChat application number is that when it is parsed into a "wxml" file, it will be in the same time. The "js" and "wxss" files with the same file name are found in the same level directory, so the "js" file needs to be pre-configured in "app.json" in time.

When writing "wxml", it can be coded according to the interface provided by the WeChat application number, most of which are the previous "div", and we can use "view" now. When you need to use other subsets, you can choose according to the interface provided by WeChat.

Use the "class" name for styling, the "id" name is basically useless here. Mainly manipulate data, do not manipulate "dom".

7. The above is the "wxml" code of the first page of the sample project. As can be seen from the figure, the amount of code to implement a page is very small.

8. The "Wxss" file is an imported style file. You can also write styles directly in it. In the example, the import method is adopted:

9. After modifying the code, refresh it once, and you can see that the "view" label without background has turned pink directly.

Note: After modifying the content under "wxml" and "wxss", you can directly see the effect by refreshing F5 directly. When modifying "js", you need to click the restart button to see the effect.

10. In addition, public styles can be directly referenced in "app.wxss".

11. The "Js" file needs to be pre-configured in the ""page"" of the "app.json" file. In order to clarify the project structure, I created four other page files in the same level directory of the "index" home page in the example project, as follows:

After the above steps, the five bottom menus in the case are all configured.

Our application account development tutorial will be continuously updated and broadcast on a rolling basis through the public account of "Business Card Box".

Follow the official account of "Business Card Box" and reply to the "Application Account" to see the latest content!

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326956227&siteId=291194637