Introduction to small program framework (Understanding)

Applets framework includes applets configuration, framework interface, scene values, WXML and WXS, etc

Two, small program configuration (proficient)

Applets are configured into global configuration, page configuration, and Sitemap configuration

1. Global configuration

The app.json file in the applets root directory is used for global configuration of wechat applets. The file content is a JSON object

The following describes common configuration options

1.1 pages

Used to specify which pages the applet consists of, each corresponding to a page path (including file name) information. File names do not need to be suffixed, the framework will automatically find the location of.json,.js,.wxml,.wxss four files to process

The first item in the options array represents the initial page (home page) of the applet. Adding or subtracting pages in a small program requires modifying the Pages array.

== Development tips ==

Create a page by writing the page path directly in the Pages option

The default project looks like this

To create the home page, category, shopping cart, my page, edit the Pages option in app.json as follows

1.2 the window

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

The default applets are shown below

The modification is displayed as follows

The 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 use the tabBar configuration item to specify the appearance of the TAB bar and the corresponding page to be displayed when the TAB is switched.

List accepts an array and can be configured with a minimum of two to a maximum of five tabs. TAB is sorted in array order, and each item is an object with the following attribute values:

Its display form is shown in the figure below

1.3.1 Prepare the bottom TAB

  1. Select the required icon in the Iconfont font icon library and click Download

Modify the corresponding image name as follows

2. Create a resource folder under the project directory and place the images in it

3. Configure the bottom TAB in app.json

Adjust the home page to the first page — initialization page

The presentation form is as follows

1.4 networkTimeout

Timeout duration of all network requests, in milliseconds.

1.5 the debug

You can enable the debug mode in the developer tool. In the console panel of the developer tool, debugging information is displayed in the form of INFO, including Page registration, Page routing, data update, and event triggering. Can help developers quickly locate some common problems

1.6 functionalPages

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

1.7 the permission

Applets interface permission related Settings. The field type is Object and the structure is:

PermissionObject structure for

The following code

The display effect is as follows

1.8 sitemapLocation

Specify the location of sitemap.json; The default is ‘sitemap.json’, which is the sitemap.json file named in the app.json directory

1.9 navigateToMiniProgramAppIdList

To use the Wx. navigateToMiniProgram interface to jump to other applets, you need to specify the list of applets to jump to in the configuration file. A maximum of 10 applets can be added.

2. Page configuration

Each applet page can also use a.json file to configure the window appearance of the page. The configuration items in the page 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

Configure the personal center page

3. Sitemap configuration

The sitemap.json file in the root directory of the applet is used to configure whether the applet and its pages are allowed to be indexed by wechat. The content of the file is a JSON object.

Iii. Framework interface (Proficient)

1.App(Object object)

Register applets. Accepts an Object parameter that specifies the life cycle callback of the applet, etc.

App() must be called in app.js, and must be called only once. Or there will be unintended consequences.

The code for app.js in the example is as follows

//app.js
App({
  onLaunch: function () {
    // Lifecycle callback -- listens for applet initialization -- globally fires only once
    // Display local storage capability
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)

    / / login
    wx.login({
      success: res= > {
        // Send res.code to the backend for openId, sessionKey, unionId}})// Get user information
    wx.getSetting({
      success: res= > {
        if (res.authSetting['scope.userInfo']) {
          // You can call getUserInfo to get the avatar nickname without popping the box
          wx.getUserInfo({
            success: res= > {
              // The res can be sent to the background to decode the unionId
              this.globalData.userInfo = res.userInfo

              // Since getUserInfo is a network request, it may not return until after page.onload
              // Callback is added here to prevent this
              if (this.userInfoReadyCallback) {
                this.userInfoReadyCallback(res)
              }
            }
          })
        }
      }
    })
  },
  onShow(options) {
    // Triggered when the small program starts, or enters the foreground display from the background
  },
  onHide() {
    // Triggered when a small program enters the background from the foreground.
  },
  onError(msg) {
    // Triggered when a script error or API call occurs in the applet
    console.log(msg)
  },
  onPageNotFound(res) {
    // Trigger when the page to be opened by the applet does not exist; For tabbar pages, use wx.switchtab-404
  },
  globalData: {
    userInfo: null}})Copy the code

2.getApp(Object object)

Get the applet global unique App instance, in the page js file to get

3.Page(Object object)

Register a page in the applet. Accepts an Object parameter that specifies the page’s initial data, lifecycle callbacks, event handlers, and so on.

Take personal centric JS as an example

// pages/user/user.js
Page({

  /** * the initial data of the page * data is the initial data used for the first rendering of the page. * When the page loads, data will be passed from the logic layer to the rendering layer as a JSON string, so the data in data must be of a type that can be converted to JSON: string, number, Boolean, object, array. * The rendering layer can bind data via WXML. * /
  data: {},/** * lifecycle function -- listen for page loading * triggered when the page is loaded. A page is called only once, and you can get the parameters in the onLoad argument to open the current page path. * /
  onLoad: function (options) {
    // options are parameters in the path to open the current page
  },

  /** * life cycle function - listen to the page when the first rendering is complete * the page when the first rendering is complete. A page is called only once, indicating that the page is ready to interact with the view layer
  onReady: function () {},/** * life cycle function - listen to page display * page display/cut foreground trigger */
  onShow: function () {},/** * life cycle function - listen for page hide * page hide/trigger when entering background */
  onHide: function () {},/** * lifecycle function - listen for page unload * triggered when page unload. * /
  onUnload: function () {},/** * Page-specific event handlers -- Listening for user pull actions * requires enablePullDownRefresh to be enabled in the window option of app.json or in the page configuration. * Pull-down refresh can be triggered by wx.startPullDownRefresh, which will trigger the pull-down refresh animation, and the effect is the same as the user's manual pull-down refresh. * Wx.stopPullDownRefresh stops the pull-down refresh of the current page */ after the data refresh is processed
  onPullDownRefresh: function () {},/** * 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 a slide within the trigger range */
  onReachBottom: function () {},/** * Users click on the upper right corner to share */
  onShareAppMessage: function (res) {
    if (res.from === 'button') {
      // from the page forward button
      console.log(res.target)
    }
    // Custom image path, can be a local file path, code package file path or network image path. PNG and JPG are supported. The display image has a 5:4 aspect ratio.
    return {
      title: 'Custom Forwarding title'.path: '/page/user? id=123'.imageUrl: ' '}},/** * listen to the user slide page event */
  onPageScroll: function () {}/** * custom function */
})
Copy the code

4, getCurrentPages ()

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

Do not attempt to modify the page stack, as this will cause routing and page state errors. Do not call getCurrentPages() while app.onlaunch is running before the Page is generated.

5. Customize components

Create a custom component that takes an Object parameter

For example, if you want a component with a list of products on the home page, you can customize the component

Click “+” to select a directory and type Components

Right-click on the Components directory, select the directory, and type ProList

Right-click the ProList directory, select New Component, and type ProList

How do you use this component?

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

Use this component in pages/home/home.wxml on the home page as if it were a normal tag

Passing values between components will be covered in a later lesson

6. Modularization

Es6’s modular approach is recommended. Exports based on the CommonJS specification and require syntax are available in the API

6.1 Define the tool module utils/index.js

Data request module and disappearing prompt box module – exposed

const baseUrl = 'http://daxun.kuboy.top'
/ * * * * * data request module interface address http://daxun.kuboy.top/apidoc to display loaded box, and then request the end loaded box * * /
export function request (url, data) {
  // Display is loading
  / / reference https://developers.weixin.qq.com/miniprogram/dev/api/ui/interaction/wx.showLoading.html
  wx.showLoading({
    title: 'Loading',})// Use promise to solve asynchronous operation problems. Async + await can also be used here
  return new Promise((resolve, reject) = > {
    // The data request method of wechat applet
    // The security domain of the applet must be configured,
    // During the development phase, the domain name, web-view(service domain name), TLS version, and HTTPS certificate can not be verified in details - Local Settings - check
    wx.request({
      url: baseUrl + url,
      data: data || {},
      success: (res) = > {
        // Hide the load
        wx.hideLoading();
        // Subsequent processing
        resolve(res.data)
      }
    })
  })
}

/** * Disappearing prompt box - by default, only text * STR prompt content * icon required icon, none, success(default), loading */ is displayed
export function Toast (str, icon) {
  // API provided by wechat
  / / reference to https://developers.weixin.qq.com/miniprogram/dev/api/ui/interaction/wx.showToast.html
  wx.showToast({
    title: str,
    icon: icon || 'none'})}Copy the code

6.2 Test on the home page

In the home page /home/home.js test, first introduce the module

4. WXML syntax reference (Proficient)

Create a new page pages/test/test

Select the toolbar of small program compilation, add compilation mode, you can render the page more quickly, easy to debug developers

1. Data binding

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

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

Data binding uses Mustache syntax to wrap variables around variables that work with:

content

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

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

3. Control properties (need to be within double quotes)

<view wx:if="{{flag}}"> </view> </view> Page({data: {
    flag: true}})Copy the code

Boolean and the number data type

If the data type is Booblean or number, wrap it with {{}}

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

5. Expression operation can be simple operation in {{}}, support 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>
Copy the code

2. List rendering

Wx :for (vUE uses V-for)

Bind an array on the component using the WX :for control property to render the component repeatedly using the data from the items in the array.

By default, the subscript variable name of the current item in the default array is index, and the variable name of the current item in the default array is item

List rendering must add the WX :key directive to specify a unique identifier for items in the list.

The key value can be set to an index value

Page({
  data: {
    teachers: [{name: 'Liu Peijun'.city: 'dalian'
      },
      {
        name: 'Wei Wah Man'.city: 'the changsha'
      },
      {
        name: 'Roh Yoo-yeop'.city: 'chongqing'
      },
      {
        name: 'Liu Chunhua'.city: 'north branch'
      },
      {
        name: 'Huang Junjian'.city: 'north branch'
      },
      {
        name: 'Tse Chin Wing'.city: 'guangzhou'
      },
      {
        name: 'li wei'.city: 'shenzhen'
      },
      {
        name: '李鹏'.city: Zhengzhou ' '
      },
      {
        name: 'Zhao Xiaokang'.city: 'nanjing'
      },
      {
        name: 'zhang lu4'.city: 'chengdu'
      },
      {
        name: '李响'.city: 'hefei'
      },
    ]
  }
})

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

The default value is item, and the default index value is index. If you need to change the value, 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>
Copy the code

3. Conditional rendering

Wx :if In the framework, use wx:if=”” to determine if the code block needs to be rendered

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

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

<view wx:if="{{len > 5}}"> 1 </view>
<view wx:elif="{{len > 2}}"> 2 </view>
<view wx:else> 3 </view>
Copy the code

Because Wx :if is a control property, you need to add it to a tag. If you want to judge multiple component labels at once, you can wrap multiple components with a single label and use the WX :if control property on it

<block wx:if="{{true}}">
  <view> view1 </view>
  <view> view2 </view>
</block>
Copy the code

== Note that == : is not a component, it is simply a wrapper element that does no rendering in the page and only accepts control properties.

Wx: If vs Hidden — (Compare V-if and V-show in Vue)

Because templates in WX :if may also contain data binding, the framework has a local rendering process when wx:if’s conditional values are switched, as it ensures that the conditional block is destroyed or re-rendered on the switch.

Wx :if is also lazy, so if the initial render condition is false, the framework does nothing and starts partial rendering only when the condition first becomes true.

Hidden, by contrast, is much simpler; components are always rendered and simply show and hide.

In general, WX: If has a higher switching cost and Hidden has a higher initial rendering cost. Therefore, hidden is better if you need to switch frequently, and wx:if is better if conditions are unlikely to change at runtime

5. WXS Syntax

WXS (WeiXin Script) is a set of scripting language for small programs. Combined with WXML, you can build the structure of a page.

WXS is a different language from JavaScript and has its own syntax, which is not consistent with JavaScript.

Those familiar with JS syntax can quickly receive and master it.

6. WXSS syntax

WXSS (WeiXin Style Sheets) is a Style language for describing the component styles of WXML.

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

To accommodate the vast majority of front-end developers, WXSS has most of the features of CSS. At the same time, WXSS expands and modifies CSS in order to be more suitable for the development of wechat small programs.

Compared to CSS, WXSS extensions have the following features:

Size of the unit

Style import

1. Size 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

== Suggestion == : Designers can use iPhone6 as the standard of visual draft when developing wechat mini programs. Note: There will inevitably be some burrs on smaller screens, so try to avoid this when developing

2. Style import

The @import statement can be used to import an external style sheet, followed by the relative path of the external style sheet to be imported, using; End of statement

3. Global versus local styles

The styles defined in app.wxSS are global and apply to each page. The styles defined in the PAGE WXSS file are local, apply only to the corresponding page, and override the same selectors in app.wxss.