Wechat applet learning notes -- development framework

1, Introduction to applet framework (understand)

If you need more tutorials, just scan the code on wechat

 

👆👆👆

Don't forget to scan the code to get the information [HD Java learning roadmap]

And [full set of learning videos and supporting materials]

 

Applet framework includes applet configuration, framework interface, scene value, WXML and WXS, etc

2, Applet configuration (proficient)

Applet configuration is divided into global configuration, page configuration and sitemap configuration

1. Global configuration

The app.json file in the applet root directory is used to globally configure wechat applets. The file content is a JSON object

Common configuration options are described below

1.1 pages

Used to specify which pages the applet consists of. Each item corresponds to the path (including file name) information of a page. There is no need to write a file suffix for the file name. The framework will automatically find and process the. JSON,. JS,. Wxml and. Wxss files of the location

There should be as many options here as there are pages
The first item of the array represents the initial page (first page) of the applet. To add / reduce pages in the applet, you need to modify the pages array.

==Development tips==

Write the page path directly in the pages option to create the corresponding page

The default project is shown in the figure

Create home page, category, shopping cart and my page, and edit the pages option in app.json as follows

1.2 window

Used to set the status bar, navigation bar, title and window background color of the applet.

The default applet is shown below

After modification, it is shown as follows:

Various attributes are shown as follows:

1.3 tabBar

If the applet is a multi tab application (there is a tab bar at the bottom or top of the client window to switch pages), you can specify the performance of the tab bar and the corresponding page displayed during tab switching through the tabBar configuration item.

list accepts an array and can only be configured with at least 2 and at most 5 tabs. tab is sorted in the order of the array. Each item is an object, and its attribute values are as follows:

The display form is shown in the figure below

1.3.1 preparing the bottom tab

  1. icon Font icon in   iconfont Font Icon Library   Select the desired icon in the, and then select download

Modify the corresponding picture name as follows

2. Create a resource folder under the project directory and put the pictures in it

3. Configure the bottom tab in app.json

Adjust the home page to the first page --- initialization page

The display form is as follows

1.4 networkTimeout

Timeout of various network requests, in milliseconds.


1.5 debug

You can open the debug mode in the developer tool. On the console panel of the developer tool, the debugging information is given in the form of info, including Page registration, Page routing, data update, event triggering, etc. It can help developers quickly locate some common problems

1.6 functionalPages

The plug-in owner applet needs to set this item to enable the plug-in function page

1.7 permission

Applet interface permission related settings. The field type is Object and the structure is:

PermissionObject structure is


The code is as follows

The display effect is as follows

1.8 sitemapLocation

Indicate the location of sitemap.json; The default is' sitemap. JSON ', that is, the sitemap.json file with the same name under the app.json peer directory

1.9 navigateToMiniProgramAppIdList

When the applet needs to jump to other applets using the wx.navigateToMiniProgram interface, it is necessary to declare the appId list of applets to jump in the configuration file, with a maximum of 10 allowed.

2. Page configuration

Each applet page can also use. JSON file to configure the window performance of this page. The configuration items in the page will overwrite the same configuration items in the window of app.json on the current page. The file content is a JSON object with the following properties

Personal center page configuration

3. sitemap configuration

The sitemap.json file in the applet root directory is used to configure whether the applet and its pages can be indexed by wechat. The file content is a JSON object. If there is no sitemap.json, all pages are allowed to be indexed by default.

3, Framework interface (proficient)

1.App(Object object)

Register applet. Accept an Object parameter, which specifies the life cycle of the applet, callback, etc.

App() must be invoked in app.js. It must be called and can only be called once. Otherwise, unexpected consequences will occur.

The app.js code in the example is as follows

//app.js
App({
  onLaunch: function () {
    // Lifecycle callback - listen for applet initialization - Global trigger only once
    // Demonstrate local storage capabilities
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)
​
    // Sign in
    wx.login({
      success: res => {
        // Send res.code to the background for openid, sessionkey and unionid
      }
    })
    // 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 => {
              // You can send res to the background and decode unionId
              this.globalData.userInfo = res.userInfo
​
              // Because getUserInfo is a network request, it may be returned after Page.onLoad
              // Therefore, a callback is added here to prevent this situation
              if (this.userInfoReadyCallback) {
                this.userInfoReadyCallback(res)
              }
            }
          })
        }
      }
    })
  },
  onShow(options) {
    // Triggered when the applet starts or enters the foreground display from the background
  },
  onHide() {
    // Triggered when an applet enters the background from the foreground
  },
  onError(msg) {
    // Triggered when a script error occurs in an applet or an error is reported in an API call
    console.log(msg)
  },
  onPageNotFound(res) {
    // Triggered when the page to be opened by the applet does not exist; For tabbar pages, use wx.switchTab - 404
  },
  globalData: {
    userInfo: null
  }
})

2.getApp(Object object)

Get the globally unique App instance of the applet and get it in the js file of the page

3.Page(Object object)

Register a page in the applet. Accept an Object type parameter, which specifies the initial data, life cycle callback, event handling function, etc. of the page.

Take personal centered js as an example

// pages/user/user.js
Page({
​
  /**
   * Initial data of the page
   * data Is the initial data used for the first rendering of the page.
   * When the page is loaded, data will be transferred from the logic layer to the rendering layer in the form of JSON string. Therefore, the data in data must be of types that can be converted into JSON: string, number, Boolean value, object and array.
   * Render layers can bind data through WXML.
   */
  data: {
​
  },
​
  /**
   * Life cycle function -- listening for page loading
   * Triggered when the page is loaded. A page can only be called once. You can get the parameters in the path of opening the current page in the onLoad parameters.
   */
  onLoad: function (options) {
    // options is to open the parameters in the current page path
  },
​
  /**
   * Life cycle function -- monitor the completion of the first rendering of the page
   * Triggered when the page is first rendered. A page can only be called once, which means that the page is ready to interact with the view layer
   */
  onReady: function () {
​
  },
​
  /**
   * Life cycle function -- monitor page display
   *  Triggered when the page is displayed / cut into the foreground
   */
  onShow: function () {
​
  },
​
  /**
   * Life cycle function -- listening for page hiding
   * Triggered when the page is hidden / cut into the background
   */
  onHide: function () {
​
  },
​
  /**
   * Life cycle function -- listen for page unloading
   * Triggered when the page is unloaded.
   */
  onUnload: function () {
​
  },
​
  /**
   * Page related event handler -- listen to user drop-down actions
   * enablePullDownRefresh needs to be enabled in the window option of app.json or in the page configuration.
   * You can trigger the pull-down refresh through wx.startPullDownRefresh, and trigger the pull-down refresh animation after calling. The effect is consistent with the user's manual pull-down refresh.
   * After processing the data refresh, wx.stopPullDownRefresh can stop the pull-down refresh of the current page
   */
  onPullDownRefresh: function () {
​
  },
​
  /**
   * Handler for bottom pull event on page
   * The trigger distance onReachBottomDistance can be set in the window option of app.json or in the page configuration.
   * This event will only be triggered once during sliding within the trigger distance
   */
  onReachBottom: function () {
​
  },
​
  /**
   * Users click the upper right corner to share
   */
  onShareAppMessage: function (res) {
    if (res.from === 'button') {
      // From within page forward button
      console.log(res.target)
    }
    // Custom picture path, which can be local file path, code package file path or network picture path. Support PNG and JPG. The aspect ratio of the display picture is 5:4.
    return {
      title: 'Custom forwarding title',
      path: '/page/user?id=123',
      imageUrl: ''
    }
  },
​
  /**
   * Listen for user sliding page events
   */
  onPageScroll: function () {
​
  }
  /**
   * Custom function
   */
})

4,getCurrentPages()

Gets the current page stack. The first element in the array is the first page, and the last element is the current page.

Do not try to modify the page stack, which will lead to routing and page state errors.
Do not call getCurrentPages() when App.onLaunch is running. The page has not been generated yet.

5. Custom components

Create a custom component and accept an Object type parameter

For example, if you need a product list component in the home page, you can customize the component

Tips: click "+" to select the directory and enter components

Right click the components directory, select the directory, and enter prolist

Right click the prolist directory, select new Component, and enter prolist

How do I use this component?

Register the components in the pages/home/home.json file on the home page

Use this component in pages/home/home.wxml on the home page, just like normal tags

The value transfer between components will be explained in subsequent courses

6. Modularization

It is recommended to use the modular method of es6. The api provides exports and require syntax based on the commonjs specification

6.1 defining the tool module utils/index.js

Data request module and disappearable prompt box module - exposure

const baseUrl = 'http://daxun.kuboy.top'
/**
 * Data request module
 * Interface address http://daxun.kuboy.top/apidoc
 * The load box is displayed first, and then the request ends. The load box disappears
 * 
 */
export function request (url, data) {
  // Show loading
  // reference resources https://developers.weixin.qq.com/miniprogram/dev/api/ui/interaction/wx.showLoading.html
  wx.showLoading({
    title: 'Loading',
  })
  // Use promise to solve the problem of asynchronous operation. You can also use async + await here
  return new Promise((resolve, reject) => {
    // Data request method of wechat applet
    // The secure domain name of the applet must be configured,
    // In the development phase, you can check "details" - "local settings" - "do not verify the request domain name, web view (business domain name), TLS version and HTTPS certificate
    wx.request({
      url: baseUrl + url,
      data: data || {},
      success: (res) => {
        // Hidden loading
        wx.hideLoading();
        // Subsequent treatment
        resolve(res.data)
      }
    })
  })
}
​
/**
 * Vanishable prompt box - only text is displayed by default
 * str Prompt content
 * icon Need icons, none, success (default), loading
 */
export function Toast (str, icon) {
  // API interface provided by wechat
  // reference https://developers.weixin.qq.com/miniprogram/dev/api/ui/interaction/wx.showToast.html
  wx.showToast({
    title: str,
    icon: icon || 'none'
  })
}

6.2 test in the first page

Test in pages/home/home.js on the home page, and introduce the module first

4, WXML syntax reference (proficient)

Create a new page pages/test/test

Select the applet compilation of the toolbar and add the compilation mode to render this page more quickly, which is convenient for developers to debug

1. Data binding

The dynamic data in WXML comes from the data of the corresponding Page.

1. Simple binding (similar to Mustache syntax in vue)

Data binding uses Mustache syntax (double braces) to wrap variables, which can act on:

content

<view> {{ message }} </view>
Page({
  data: {
    message: 'Hello MINA!'
  }
})

  1. Component properties (need to be within double quotes)
<view id="item-{{id}}"> </view>
Page({
  data: {
    id: 0
  }
})

3. Control attribute (need to be within double quotation marks)

<view wx:if="{{flag}}"> If the condition is true, I will show it </view>
Page({
  data: {
    flag: true
  }
})

4.boolean and number data types

If the data type is booblean or number, you need to use {}} package

<checkbox checked="{{false}}"> </checkbox>
<view data-num = "{{100}}"></view>

5. Expression operation can be performed in   {{}}   It supports ternary operation, arithmetic operation, logical judgment, string operation, etc

<view test="{{flag ? true : false}}"> attribute </view>

<view> {{a + b}} + {{c}} + d </view>

<view wx:if="{{len > 5}}"> </view>

<view>{{"hello" + name}}</view>

2. List rendering

wx:for (use v-for in vue)

Bind an array with the wx:for control attribute on the component to render the component repeatedly with the data of each item in the array.

The index variable name of the current item of the default array is index by default, and the variable name of the current item of the array is item by default

List rendering must add the wx:key instruction to specify the unique identifier of the item in the list.

The key value can be set as the index value

Page({
  data: {
    teachers: [
      {
        name: 'Liu Peijun',
        city: 'Dalian'
      },
      {
        name: 'Wei Huawen',
        city: 'Changsha'
      },
      {
        name: 'Lu Youye',
        city: 'Chongqing'
      },
      {
        name: 'Chun Hua Liu',
        city: 'Beike'
      },
      {
        name: 'Huang Junjian',
        city: 'Beike'
      },
      {
        name: 'Xie Jinrong',
        city: 'Guangzhou'
      },
      {
        name: 'Li Wei',
        city: 'Shenzhen'
      },
      {
        name: 'Li Peng',
        city: 'Zhengzhou'
      },
      {
        name: 'Xiao Kang Zhao',
        city: 'Nanjing'
      },
      {
        name: 'Zhang Lu',
        city: 'Chengdu'
      },
      {
        name: 'Li Xiang',
        city: 'Hefei'
      },
    ]
  }
})

<view wx:for="{{teachers}}" wx:key="index">
  <text>{{index}}</text>
  -
  <text>{{item.city}}</text>
  -
  <text>{{item.name}}</text>
</view>

The default option is item and the default index value is index. If you need to change it, you can use the following methods

<view wx:for="{{teachers}}" wx:for-item="itm" wx:for-index="idx"  wx:key="idx">
  <text>{{idx}}</text>
  -
  <text>{{itm.city}}</text>
  -
  <text>{{itm.name}}</text>
</view>

3. Conditional rendering

wx:if in the framework, use wx:if = "" to determine whether the code block needs to be rendered

<view wx:if="{{flag}}"> True </view>

You can also add an else block with wx:elif and wx:else

<view wx:if="{{len > 5}}"> 1 </view>
<view wx:elif="{{len > 2}}"> 2 </view>
<view wx:else> 3 </view>
Because wx:if is a control attribute, you need to add it to a tag. If you want to judge multiple component labels at one time, you can wrap multiple components with a < block / > label and use wx:if control attribute on it
<block wx:if="{{true}}">
  <view> view1 </view>
  <view> view2 </view>
</block>
==Note = =: < block / > is not a component. It is just a wrapper element. It will not render in the page and only accepts control attributes.

wx:if vs hidden  --- (compare v-if and v-show in vue)

Because the template in wx:if may also contain data binding, when the condition value of wx:if is switched, the framework has a local rendering process, because it will ensure that the condition block is destroyed or re rendered during switching.

At the same time, wx:if is also inert. If the initial rendering condition is false, the framework does nothing and starts local rendering when the condition becomes true for the first time.

In contrast, hidden is much simpler. Components will always be rendered, just simple control of display and hiding.

In general, wx:if has a higher switching cost and hidden has a higher initial rendering cost. Therefore, hidden is better if frequent switching is required, and wx:if is better if the conditions are unlikely to change at runtime

5, WXS syntax (understand)

WXS (WeiXin Script) is a script language for small programs. Combined with WXML, the structure of pages can be constructed.

WXS and JavaScript are different languages and have their own syntax, which is not consistent with JavaScript.

Familiar with js syntax can quickly receive and master it.

6, WXSS syntax

WXSS (WeiXin Style Sheets) is a set of style languages used to describe the component styles of WXML.

WXSS is used to determine how WXML components should be displayed.

In order to adapt to the majority of front-end developers, WXSS has most of the features of CSS. At the same time, in order to be more suitable for developing wechat applet, WXSS has expanded and modified CSS.

Compared with CSS, WXSS extends the following features:

Dimension unit

Style import

1. Dimension unit

Rpx (responsive pixel): it can be adaptive according to the screen width. The specified screen width is 750rpx. If the screen width is 375px and there are 750 physical pixels on the iPhone 6, then 750rpx = 375px = 750 physical pixels and 1rpx = 0.5px = 1 Physical pixel


==Suggestion = =: when developing wechat applet, designers can use iPhone6 as the standard of visual draft.
==Note = =: there will inevitably be some burrs on the small screen. Please try to avoid this situation during development

2. Style import

Use the @ import statement to import the external style sheet, @ import followed by the relative path of the external style sheet to be imported, with; Indicates the end of the statement

3. Global style and local style

The style defined in app.wxss is a global style, which acts on every page. The style defined in the wxss file of page is a local style, which only works on the corresponding page and overrides the same selector in app.wxss.

If you need more tutorials, just scan the code on wechat

 

👆👆👆

Don't forget to scan the code to get the information [HD Java learning roadmap]

And [full set of learning videos and supporting materials]

 

 

Tags: Java Front-end Mini Program

Posted on Tue, 02 Nov 2021 06:02:16 -0400 by flyhoney