Insights into applets

Posted by mwd2005 on Sun, 23 Feb 2020 10:29:42 +0100

Insights into applets

Counter war

What is applet

Small program is an application that can be used without downloading and installation. It realizes the dream of "within reach" of the application. Users can scan or search the application to open it. It also embodies the concept of "go after use". Users don't need to worry about whether to install too many applications. Applications will be everywhere, ready to use, but without installation or uninstallation.

Types of applets

WeChat applet, Alipay applet, headline applet, Baidu applet, QQ applet

The history of small programs

time Remarks
2016-09-21 Inside wechat applet
2016-11-03 Wechat app public beta
2017-01-09 Wechat applet officially launched
2017-09-20 Alipay applet beta
2017-12-28 Wechat applet home page pull-down entry and wechat applet Online
2018-01 Massive promotion of wechat games - jump
2018-02 Blessing applets and games
2018-03 Xiaomi, ZTE, Huawei, Jinli, Lenovo, Meizu, Nubia, OPPO, vivo, one plus ten mobile phone manufacturers
We launched the fast app together. Although the names are different, they are essentially small programs
2018-07 Baidu app goes online
2018-09-16 Headline applet Online
2019-06 QQ applet Online

Advantages of applets

For developers, the threshold of small program development is relatively low, and the difficulty is less than that of APP. It can meet the requirements of simple basic applications, and is suitable for the conversion of offline shops of life services and non rigid low-frequency applications.
For users, it can save time cost and memory space; for developers, it can also save development and promotion costs.

Configure applet

Global configuration
The configuration in app.json is equivalent to the route in vue
Write the page path directly in the pages option to create the corresponding page

{
  "pages": [
    "pages/kind/kind",
    "pages/home/home",
    "pages/cart/cart",
    "pages/user/user",
    "pages/details/details",
    "pages/map/map"
  ],
  "window": {
    "navigationBarBackgroundColor": "#f66",
    "navigationBarTextStyle": "white",
    "navigationBarTitleText": "Tesco",
    "backgroundColor": "#efefef",
    "backgroundTextStyle": "dark",
    "backgroundColorTop": "#0f0",
    "onReachBottomDistance": 50
  },
  "tabBar": {
    "color": "#333",
    "selectedColor": "#f66",
    "backgroundColor": "#efefef",
    "borderStyle": "white",
    "list": [
      {
        "pagePath": "pages/home/home",
        "text": "home page",
        "iconPath": "resources/home.png",
        "selectedIconPath": "resources/home_active.png"
      },
      {
        "pagePath": "pages/kind/kind",
        "text": "classification",
        "iconPath": "resources/kind.png",
        "selectedIconPath": "resources/kind_active.png"
      },
      {
        "pagePath": "pages/cart/cart",
        "text": "Shopping Cart",
        "iconPath": "resources/cart.png",
        "selectedIconPath": "resources/cart_active.png"
      },
      {
        "pagePath": "pages/user/user",
        "text": "My",
        "iconPath": "resources/user.png",
        "selectedIconPath": "resources/user_active.png"
      }
    ]
  },
  "networkTimeout": {
    "request": 6000,
    "connectSocket": 6000,
    "uploadFile": 6000,
    "downloadFile": 6000
  },
  "permission": {
    "scope.userLocation": {
      "desc": "Allow location"
    }
  },
  "navigateToMiniProgramAppIdList": [
    "wx5dfe0dd623d5ae6b"
  ],
  "style": "v2",
  "sitemapLocation": "sitemap.json",
  "debug": false
}

Sitemap.json here is a file, which is mainly 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. If there is no sitemap.json, all pages are allowed to be indexed by default.
Page configuration
Pages sub file configuration pages
Configure local styles

{
  "navigationBarBackgroundColor": "#ff7001",
  "navigationBarTextStyle": "white",
  "navigationBarTitleText": "Tesco-home page",
  "backgroundColorTop": "#efefef",
  "backgroundTextStyle": "light",
  "enablePullDownRefresh": true,
  "onReachBottomDistance": 50,
  "disableScroll": false,
  "usingComponents": {
    "prolist": "/components/prolist/prolist"//Sub component lead in path
  }
}

The js file here is mainly used to process the initial data of the page, life cycle callback, event processing functions, etc.

Page({

  /**
   * Initial data of the page
   * data Is the initial data used by the first rendering of the page.
   * When the page is loaded, data will be passed from the logical layer to the rendering layer in the form of JSON string, so the data in data must be of the type that can be converted to JSON: string, number, Boolean value, object, array.
   * Render layers can bind data through WXML.
   */
  data: {

  },

  /**
   * Life cycle function -- listening to page loading
   * Triggered when the page is loaded. A page can only be called once, and the parameters in the path to open the current page can be obtained in the parameters of onLoad.
   */
  onLoad: function (options) {
    // options is to open the parameters in the current page path
  },

  /**
   * Life cycle function -- listen to 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 -- monitor page hidden
   * Triggered when the page is hidden / cut into the background
   */
  onHide: function () {

  },

  /**
   * Life cycle function -- monitor page unloading
   * Triggered when the page is unloaded.
   */
  onUnload: function () {

  },

  /**
   * Page related event processing function -- listening to user pull-down action
   * You need to enable enablePullDownRefresh in the window option of app.json or in the page configuration.
   * The pull-down refresh can be triggered by wx.startPullDownRefresh, and the pull-down refresh animation can be triggered after calling, with the same effect as the manual pull-down refresh.
   * When the data refresh is finished, wx.stopPullDownRefresh can stop the pull-down refresh of the current page
   */
  onPullDownRefresh: function () {

  },

  /**
   * Handling function of page pull bottom event
   * You can set the trigger distance onreachbuttomdistance 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 in 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 displayed image is 5:4.
    return {
      title: 'Custom forwarding title',
      path: '/page/user?id=123',
      imageUrl: ''
    }
  },

  /**
   * Listen to user sliding page events
   */
  onPageScroll: function () {

  }
  /**
   * Custom function
   */
})

If you set some global data in the global app.js file, for example, get the basic information of the device

//app.js
App({
  onLaunch: function () {
    //Get basic information of the device
    this.getDeviceInfoFn()
  },
  getDeviceInfoFn() {
    wx.getSystemInfo({
      success: (res) => {
        console.log(res)
        // Modify global variable data
        this.globalData.deviceinfo = res
      }
    })
  },
  globalData: {
    userInfo: null,
    deviceinfo:null//Set a global device information variable to accept
  },

Send asynchronous request

It is recommended to use the modular method of es6. The api provides exports and require syntax based on the commonjs specification
Define tool module utils/index.js

// Interface address 
const baseUrl = 'Interface address'
//Expose global approach
export function request(options){
  //Destructuring assignment
  const {url,data}=options;
  wx.showLoading({
    title: 'Loading',
  })
  // Callback function, promise, generator + yield, async+await
  return new Promise((resolve, reject) => {
    wx.request({
      url: baseUrl + url,
      data: data || {},
      success: (res) => {
        // Asynchronous operation successfully called resolve
        resolve(res)
      },
      fail: (err) => {
        // Asynchronous operation failed call reject
        reject(err)
      },
      complete: () => {
        // Cancel refresh on success and failure
        wx.hideLoading()
      }
    })
  })
}

Common components in applets

Request and rendering of the data of the first page carousel

<swiper
  indicator-dots="{{true}}" autoplay="{{true}}" circular="{{true}}" 
  duration="{{500}}">
  <block wx:for="{{bannerlist}}" wx:key="index">
    <swiper-item >
      <image src="{{'http://.....kuboy.top' + item}}"></image>
    </swiper-item>
  </block>
</swiper>
<prolist></prolist>//Subcomponent call

map

<map 
  class="map" 
  longitude="{{longitude}}" 
  latitude="{{latitude}}"
  scale="15"
  markers="{{markers}}"
  controls="{{controls}}"
  bindcontroltap="controlshandler"//Custom click event
  ></map>
  //Get latitude and longitude
  data: {
    longitude: '118.8205719000', // longitude
    latitude: "31.8839713500", // dimension
    markers: [{
      id: 1, //This id will be returned when the marker clicks the event callback
      longitude: '118.8205719000', // longitude
      latitude: "31.8839713500", // dimension
      title: 'pagoda will stop river monster', // Ignore when clicking the marker prompt call out appears
      iconPath: '/resources/zuobiao.png', 
      width: 40,
      height: 40,
      callout: {
        content: 'pagoda will stop river monster',
        color: '#f66',
        fontSize: 14,
        borderRadius: 5,
        borderWidth: 3,
        bgColor: 'white',
        padding: 10,
        display: 'BYCLICK', //  'BYCLICK': Click to display; 'ALWAYS': ALWAYS
        textAlign: 'center'
      }
    }],
    controls: [{//controls is the display control on the map. The control does not move with the map
      id: 1,
      position: { // left,top
        left: screenWidth-70,  // Get the width and height of the device - get the basic information of the device
        top: screenHeight - 150,
        width: 40,
        height: 40
      },
      iconPath: '/resources/xingzhuang.png',
      clickable: true // Control default can not be clicked
    }]
  },
  //Custom click event
  controlshandler(event) {
    console.log(event)
    //id number of the positioning button to determine whether to click
    if (event.controlId === 1) {
      //Call to get the current latitude and longitude
      wx.getLocation({
        success: (res) => {
          console.log(res)
          //Destructuring assignment
          const {longitude,latitude} = res
          this.setData({
            longitude, latitude,
            markers: [{
              id: 1, //This id will be returned when the marker clicks the event callback
              longitude: longitude, // longitude
              latitude: latitude, // dimension
              title: 'pagoda will stop river monster', // Ignore when clicking the marker prompt call out appears
              iconPath: '/resources/zuobiao.png', 
              width: 40,
              height: 40,
              callout: {
                content: 'pagoda will stop river monster',
                color: '#f66',
                fontSize: 14,
                borderRadius: 5,
                borderWidth: 3,
                bgColor: 'white',
                padding: 10,
                display: 'BYCLICK', //  'BYCLICK': Click to display; 'ALWAYS': ALWAYS
                textAlign: 'center'
              }
            }]
          })
        }
      })
    }
  },

Published 1 original article · praised 0 · visited 7
Private letter follow

Topics: JSON Mobile less Vue