Make writing a habit together! This is my first day to participate in the “Gold Digging Day New Plan · April More text challenge”, click to see the details of the activity

Last month, I wrote a company’s wechat small program project to strike while the iron is hot and share a development tutorial, hoping to help students who have no small program development experience. For students with VUE experience, after reading this article, they can directly get started.

This article will be completed by asking questions to make learning easier!

Searching for Tips leads directly to pit avoidance experience.

Applets framework principle?

View layer plus logic layer, view layer for rendering, logic layer for events. The rendering layer and the logic layer are in two threads, communicating via the wechat client.

The goal of the apPLETS development framework is to enable developers to develop services with native APP experience in wechat in as simple and efficient a way as possible. The whole small program framework system is divided into two parts: logic layer (App Service) and View layer (View). Applets provide their own view layer description languages WXML and WXSS, as well as a Javascript-based logic layer framework, and provide data transfer and event systems between the view layer and logic layer, allowing developers to focus on data and logic.

Why can’t we use Alert in wechat mini program?

Because there are no window and Document objects in the applet

The logical layer of the applets framework does not run in the browser, so JavaScript in the Web some capabilities are not available, such as Window, document and so on.

Why can’t div be used in applets?

Because the WXML of the small program is not native HTML, but an XML-based syntax implemented by wechat itself. The label language specification of wechat applet is used in the development process. Here’s an example:

  • The view tag replaces the div
  • The image tag replaces img

What is the difference between the applet JS runtime environment and the browser JS runtime environment?

The js of the developer tool in the applets runs in nw.js, and the JS of the browser runs in the V8 engine of the browser.

Wechat applets run on a variety of platforms: iOS/iPadOS wechat client, Android wechat client, Windows PC wechat client, Mac wechat client, applets hardware framework and wechat developer tools for debugging, etc. The script execution environment and the environment used for component rendering are different under different runtime environments, and the performance is also different: On iOS, iPadOS, and Mac OS, the JavaScript code in the applet logic layer runs in JavaScriptCore, and the view layer is rendered by WKWebView, IOS 14, iPad OS 14, Mac OS 11.4, etc. On Android, the JavaScript code of the small program logic layer runs in V8, and the view layer is rendered by the wechat self-developed XWeb engine based on Mobile Chromium kernel. On Windows, the small program logic layer JavaScript and view layer both use Chromium kernel; On the development tool, the JavaScript code of the applet logic layer is run in nw.js and the view layer is rendered by Chromium Webview.

Runtime environment Logic layer Rendering layer
iOS JavaScriptCore WKWebView
The android V8 Chromium Custom kernel
Applets developer tools NWJS Chrome WebView

Pre – development of applets?

  1. Sign up for an app account using an email address that has not yet been registered with a public account or app
  2. Add developers: small program management background – management – member management – project members
  3. Developers download the latest version of wechat developer tools and fill in a template (typescript enabled) to generate the APPID project
  4. Familiar with wechat developer tool interface functions

Tips: Wechat developer tool interface has a lot of content, so you can separate the simulator interface and display it in two interfaces

What file types are associated with applets?

type describe
.WXML Tag language, combined with basic components and event systems, can build the structure of a page
.WXSS Style language, used to describe the component styles of WXML
.json Page configuration, for example, navigation bar title, and whether to support drop-down refresh
.js Js logic, event interaction logic, HTTP request, etc

Tips: iOS devices do not support the maxLength attribute of the input tag very well. When the input method is Chinese, pinyin will be calculated as the value length. The alternative is to listen for length changes in the bindinput method

How to add a page?

In applets developer tools, go to app.json in the root directory of your project and configure the Page field

  {
      "pages": ["pages/test/index"]},Copy the code

After saving, a test folder is automatically generated in the Pages directory, which contains the four files required for a page. tips:

  1. Automatic file creation can only be triggered in wechat developer tools, not in VScode
  2. If you use VScode to develop applets, you need to install the applets assistant plug-in

How to set the bottom TAB bar?

Configure the tabBar field in app.json

  "tabBar": {
  "color": "#bfbfbf"."selectedColor": "#2056F0"."list": [{"pagePath": "pages/home/index"."text": "First page"."iconPath": "/images/home.png"."selectedIconPath": "/images/home2.png"
    },
    {
      "pagePath": "pages/customer/index"."text": "Client"."iconPath": "/images/customer.png"."selectedIconPath": "/images/customer2.png"
    },
    {
      "pagePath": "pages/setting/index"."text": "A place"."iconPath": "/images/mine.png"."selectedIconPath": "/images/mine2.png"}}]Copy the code

Other page configurations can also be configured in app.json

How to set uniform background color?

Set in app.wxss:

page {
  background-color: #f5f7fa;
}
Copy the code

CSS unit

RPX (Responsive Pixel) : ADAPTS to the screen width. Specify a screen width of 750rpx. For example, on iPhone6, the screen width is 375px and there are 750 physical pixels, then 750rpx = 375px = 750 physical pixels and 1rpx = 0.5px = 1 physical pixel.

Tips: Gap is not supported on ios devices

Life cycle function of applets?

function describe
onLoad Executed when the page loads, initialization data is placed here
onReady Executed when the first rendering of the page is complete
onShow The logic that is executed when the page is displayed and triggered when the page is re-entered is placed here
onHide Executed when the page is hidden

How is bidirectional binding of applets different from VUE?

View update is automatically triggered when bidirectional binding data changes in VUE. In applets, you need to call this. SetData method to start view update

Message prompt box in applets

wx.showToast({
  title: "Request successful".icon: "success".duration: 1500});Copy the code

Tips: In actual use, it will be found that the message prompt box cannot be executed according to the set duration, we can manually hide the message prompt box:

setTimeout(function () {
  wx.hideToast();
  wx.navigateBack({
    delta: 1}); },1000);
Copy the code

Message prompt box

Modal dialog box in applets

wx.showModal({
  title: "Tip".content: "This is a modal popover".success(res) {
    if (res.confirm) {
      console.log("User hits OK");
    } else if (res.cancel) {
      console.log("User hit Cancel"); }}});Copy the code

Modal dialog box

How does the applet update the page?

Call the setData method for a local data refresh

How do you pass data between pages?

  1. Add parameters after the URL of the page to transfer parameters between pages
/ / a page
  wx.navigateTo({
    url: '.. /customerDetail/index? customerId='+ id,
    success: function(res) {}})/ / b page
  onLoad: function (options) {
    const customerId = options.customerId
  }
Copy the code
  1. Implement a change global update with app.GlobalData
/ / a page
app.globalData.userInfo = { name: "testName".age: 18 };
/ / b page
const app = getApp();
const name = app.globalData.userInfo.name;
Copy the code
  1. The use of storage

How do you implement data binding?

// WXML
<view> {{ message }} </view>;
// js
Page({
  data: {
    message: "Hello MINA!",}});Copy the code

Data binding

How is event binding implemented?

Bindtap, catchtap, etc

Events are classified into bubbling events and non-bubbling events: Bubbling events: When an event is triggered on a component, the event is passed to the parent node. Non-bubbling event: When an event on a component is fired, the event is not passed to the parent node.

// WXML
<view bindtap="viewTap"> click me </view>;
// js
Page({
  viewTap: function () {
    console.log("view tap"); }});Copy the code

event

How do I pass parameters to events?

Event objects can carry additional information such as ID, dataset, and Touches.

// WXML
<view wx:for="list" data-name="{{item.name}}" bindtap="ontap"></view>
// js
ontap:function(e){
  const itemName = e.currentTarget.dataset.name
}
Copy the code

What is the difference between bindtap and catchtap?

  1. Bindtap binds events, allowing them to bubble
  2. The child uses Catchtap and the parent uses bindtap when both the child node and the parent node have click events

What are the ways of page hopping?

Routing method describe
wx.navigateTo Keep the current page and go to a page in the application. But you cannot jump to the Tabbar page. Up to 10 page stacks
wx.redirectTo Close the current page and switch to a page in the application. However, jumping to the Tabbar page is not allowed
wx.switchTab Jump to the tabBar page and close all other non-Tabbar pages
wx.navigateBack Close the current page and return to the previous page or multi-level page
wx.reLaunch Close all pages and open to a page within the app

How do I do conditional rendering?

<view wx:if="{{condition}}">Copy the code

Tips: Frequent rendering is replaced with hidden, similar to the difference between V-if and V-show conditional rendering in VUE

How do I do loop rendering?

  <view wx:for="{{list}}" wx:key="id" wx:for-item="user">
    {{user.name}}
  </view>
Copy the code

The list of rendering

How do I request data?

Configure the server domain name in the applet Management background – Development – Development Management – Development Settings – Server Domain name – Request legitimate domain name

wx.request({
  url: "https://www.test.com/api/userList".header: {},
  data: {
    pageIndex: 1.pageSize: 10,},timeout: 20000.success: function (res) {
    // Successful callback
  },
  fail: function (e) {
    // Failed callback}});Copy the code

tips:

  1. GET requests to pass arrays are encoded, so a POST request is used to pass array parameters
  2. The field values in the header cannot be transmitted after encoding. You can use the encodeURIComponent method
  3. Support promise encapsulation

wx.request

How do I upload pictures?

  1. Configure the server domain name in the applet management background – Development – Development Management – Development Settings – Server domain name -uploadFile legitimate domain name
  2. Use wx.uploadFile, usually with wx.chooseImage or other methods:
wx.uploadFile({
  url: "url".filePath: "filePaths".name: "file".formData: {
    user: "test",},success: function (res) {},
  fail: function (e) {},
  complete: function (res) {}});Copy the code

Tips: Note the maximum image size supported by the backend. The size of images taken by different phones varies greatly, from 6M for Android to 10M for IOS

wx.uploadFile wx.chooseImage

How do I play the recording?

const audioContext = wx.createInnerAudioContext({
  useWebAudioImplement: true}); audioContext.src ="audioUrl";
audioContext.play(); / / play
Copy the code

wx.createInnerAudioContext

How to implement the pull down refresh?

Set to allow pull-down refresh in json file:

"enablePullDownRefresh": true.Copy the code

Add a pull-down refresh callback to the js file:

onPullDownRefresh: function () {
  // Pull back
  // ...
  // Stop the pull-down refresh after the callback is complete
  wx.stopPullDownRefresh();
},
Copy the code

Typically used for drop-down page refresh requests.

How to implement bottom update?

Add the onReachBottom callback to the js page:

onReachBottom: function () {
  // Bottom correction
}
Copy the code

Generally used when the list data is too much, paging load.

How to introduce NPM packages such as Moment?

  1. Execute at the root of the applet:
  npm i moment -S
Copy the code
  1. Find – Tools – Build NPM in the wechat Developer tools interface

How to use developer tools to develop enterprise micro channel applets?

  1. Wechat developer Tools – Tools – Plug-ins – Add enterprise wechat small program plug-ins
  2. Select the enterprise currently in use

Tips:

  1. Developers always see the development version when they open the small program in the enterprise wechat
  2. Give beta access to testers instead of developers for the same reason
  3. The personal information in the corporate address book obtained by wechat does not contain an employee’s name or phone number, but only id and alias information

When are applets destroyed?

If the user hasn’t used the applet in a long time, or if system resources are tight, the applet is “destroyed,” which is to stop running completely. Specifically, it includes the following situations: When a small program enters the background and is “suspended”, if it does not enter the foreground again for a long time (currently 30 minutes), the small program will be destroyed. When small programs occupy too much system resources, they may be destroyed by the system or recycled by the wechat client. On iOS, when the wechat client receives a memory alarm within a certain period of time, it destroys the small program according to certain policies and prompts the user to “Run out of memory. Please open the small program again”. Specific strategies will continue to be adjusted and optimized. It is recommended that applets use wx.onMemoryWarning to listen for memory alarm events and clean up memory if necessary. Basic library 1.1.0 or later, 1.4.0 or later: When a user enters a small program through the scan and forward portals (scenario values: 1007, 1008, 1011, 1025) and exits without setting the top small program, the small program will be destroyed.

Tips: after the small program opened, in a short period of time to enter the small program will not be executed from scratch, but will directly lift the page in memory to run in the foreground.

Tips: Implement version updates with wx.getUpdateManager

Environmental control of applets?

  • Development version Scan the preview TWO-DIMENSIONAL code on the developer tool to generate the development version in the small program management background – Management – Member Management – Project members add developers in the small program management background – management – Version Management – Development version view the experience version of the two-dimensional code

  • Experience version Click the uploaded code generation experience version on the developer tool to add experience members in the small program management background – Management – member management – project members

  • Review the review details in the small program management background – Administration – Version Management – Review version

  • For official version, view the online version details in admin – Version Management – Online Version

    Tips:

    1. When setting the experience version, pay attention to setting the page path. You can only provide experience on a single page
    2. When submitting for review, submit pictures and operation videos at the same time, which is easier to pass the review
    3. The version submitted for review must be able to enter the page normally without any permissions (tourist identity can be provided), otherwise it cannot be approved
    4. The generated development preview code expires within 30 minutes, and the experience code remains valid for a long time

Applets release process?

Click upload code in the wechat developer tool to view the current version and submit it for review in the mini program management background – Management – Version Management – Development version view the review details in the mini program management background – Management – Version Management – Review version

Tips: small program release support grayscale release, you can specify micro signal release, very nice!

Write in the last

If it is a new wechat small program project, it is suggested to directly use the native way of wechat small program development. After reading a lot of articles mocking the bad use of native programs, I find that by 2022, wechat official has repaired and optimized most functions, especially the very important functions, and there is no big obstacle to the native development. Pay attention to little sister, learn together!