Summary of common knowledge points of WX applet

1. Advantages and Disadvantages of WX Mini Program

1. Advantages

(1) WeChat assistant, easy to promote. In WeChat, mini programs have many entrances, such as nearby mini programs, mini program codes, sharing, discovery-mini programs, and more than 50 entrances. These entrances help companies better obtain traffic for conversion and monetization.
(2) Easy to use. When users use mini programs, they only need one click to use them, which is more in line with users' needs for convenience and speed. Therefore, the number of users of mini programs continues to increase.
(3) The experience is good and close to the native app experience. In the WeChat ecosystem, mini programs can instantly kill H5 pages in terms of functionality and experience. H5 pages often suffer from lags, delays, slow loading, insufficient permissions, etc. However, these problems do not occur in mini programs.
(4) Lower costs. From development costs to operation and promotion costs, the cost of mini programs is only one-tenth of that of APPs, which is a major advantage for both entrepreneurs and traditional merchants.

2. Insufficient

(1) The size of a single package is limited to 2M, which makes it impossible to develop large-scale applications. The maximum subcontracting method is 20M (this value is always changing, please refer to the official website).
(2) It needs to be reviewed and put on the shelf like an app, which is more troublesome than the release of H5.
(3) Everything is restricted by WeChat. For example, it cannot be shared directly to Moments, and mini programs are not allowed when points or virtual transactions are involved.

2. Project structure of WX applet

1.pages:
        (1) wxml: where the mini program interface structure is written
        (2) wxss: where the mini program style is written
        (3) json: where the interface configuration is written
        (4) js: where the interface logic is written
2.utils : Where to write tool classes
3.app.js: Where to create program instances
4.app.json: Where to write global configuration
5.app.wxss: Where to write global styles
6.project.config.json: Project configuration file

3. The difference between js in mini program, browser and node

1. js in the browser

        (1)ES

        (2)DOM

        (3)BOM

2. js in node

        (1)ES

        (2)NPM

        (3)Native

3.js in wx applet

        (1)ES

        (2) Mini program framework

        (3) Mini program API

The entry file for the execution of the mini program is app.js. And the running order of the files will be determined based on the module order of require.

4. What is the difference between data rendering in mini programs and in browsers?

        1. Single-threaded rendering in the browser

        2. The running environment in the mini program is divided into the rendering layer and the logic layer. WXML and WXSS work in the rendering layer, and js works in the logic layer.

        When displayed on the page, use the interpolation expression { { }}

5. Briefly describe the communication model of the mini program

        The rendering layer and logic layer of the mini program are managed by two threads respectively:

        The interface of the rendering layer uses WebView for rendering;

        The logic layer uses JsCore threads to run JS scripts.

        A small program has multiple interfaces, so there are multiple WebView threads in the rendering layer. The communication between these two threads will be relayed through the WeChat client (Native will also be used to refer to the WeChat client below), and the logic layer will send network requests. Also forwarded via Native.

6. How to optimize the first loading speed of the mini program (subpackage loading)

1.What is subpackage loading?

        In some cases, developers need to divide the small program into different sub-packages, package them into different sub-packages when building, and load them on demand when users use them. The content of the main package will be loaded when you access the mini program for the first time, and the content of the subpackage will only be loaded when you access the subpackage interface.

2. Why use subcontracting?

        (1) The size of a single mini program package is limited to 2M, and can be expanded to a maximum of 20M using sub-packaging (when building a large APP)

        (2) Optimize the speed of loading the mini program for the first time. Contents that do not need to be loaded for the first time can be placed in sub-packages, which can improve the performance of the mini program (when performance requirements are relatively high)

3. How to use subcontracting

(1) Directory structure

 (2) Configuration (just need to configure it in app.json)

{ 
"pages":[ "pages/index", "pages/logs" ],
 "subpackages": [ 
    { 
        "root": "packageA", 
        "pages": [ "pages/cat", "pages/dog" ] 
    }, 
    {   
        "root": "packageB", 
        "name": "pack2", 
        "pages": [ "pages/apple", "pages/banana"] 
    } 
] 
}

(3) Restrictions on subcontracting

        a. Sub-packages cannot reference each other’s js

        b. The main package cannot reference sub-packaged js

(4) Independent subcontracting

        Subcontracting that does not depend on the main package

        When configuring subcontracting, add the independent configuration to declare it as independent subcontracting.

(5) Subcontracting preloading

        When routing to a certain interface, you may need to load the content of a certain subpackage to improve the speed of accessing this subpackage.

        Just configure it in app.json       

{    
    "pages": ["pages/index"],   
    "subpackages": [      
        {
            "root": "important",
            "pages": ["index"]
        },{
            "root": "sub1",
            "pages": ["index"],
        },{
            "name": "hello",
            "root": "path/to",
            "pages": ["index"]
        }, {
            "root": "sub3",
            "pages": ["index"]
        },{
            "root": "indep",
            "pages": ["index"],
            "independent": true
        }
    ],   
    "preloadRule": {      
        "pages/index": {
            "network": "all",
            "packages": ["important"]
        },      
        "sub1/index": {        
            "packages": ["hello", "sub3"]
        },      
        "sub3/index": {        
            "packages": ["path/to"]          
        },      
    "indep/index": {        
        "packages": ["__APP__"]      
     }    
  }
}

7. How to configure tabbar and precautions

        1. Configure the tabbar ( it should be noted that the icon of the tabbar cannot be an online address and needs to be prepared in advance and placed in the project. Under normal circumstances, these static resources can only be placed in the assets folder )

        2. Write it in the app.json file in the root directory. Please note that there must be at least two in the list and only five at most.

        3. Each object in the list has four attributes

                (1) pagePath: the path to the corresponding page

                (2) text: displayed text

                (3) iconPath: The location path of the icon when not selected

                (4) selectedIconPath: The location path of the icon when selected

"tabBar": {
    "color":"",
    "selectedColor": "#f00",
    "list": [
      {
      "pagePath": "pages/index/index",
      "text": "首页",
      "iconPath": "./assets/shouye.png",
      "selectedIconPath": "./assets/shouye1.png"
    },
    {
      "pagePath": "pages/logs/logs",
      "text": "log",
      "iconPath": "./assets/bianji.png",
      "selectedIconPath": "./assets/bianji1.png"
    },
    {
      "pagePath": "pages/home/home",
      "text": "我的",
      "iconPath": "./assets/grzl.png",
      "selectedIconPath": "./assets/grzl1.png"
    }
  ]
  }

8. Commonly used components (tags) in wxml

        The view tag is the most commonly used tag in our development process. This is equivalent to the div in Html.

        The text tag is also commonly used in our development. This is equivalent to span in Html.

        The image tag is equivalent to img in our Html.

9. The difference between wxss and css

Compared with CSS, the features of WXSS extensions are:    

        1. Size unit : rpx (responsive pixel): can be adapted according to the screen width. The specified screen width is 750rpx. For example, on iPhone6, the screen width is 375px and there are 750 physical pixels in total, then 750rpx = 375px = 750 physical pixels, 1rpx = 0.5px = 1 physical pixel

        2. Style import : Use @importthe statement to import the external style sheet, @importfollowed by the relative path of the external style sheet that needs to be imported, and ;end the statement with "."

For example: objects to be imported

/** common.wxss **/
.small-p {
  padding:5px;
}

 Import location

/** app.wxss **/
@import "common.wxss";
.middle-p {
  padding:15px;
}
内联样式

10. Event binding and parameter passing in WeChat applet

        1. Event definition: Binding events in a mini program can start with bind and then follow the event type. For example, bindtap binds a click event, and the corresponding value is a string. You need to define a function with the same name in the page constructor. After the event is triggered, the content of the corresponding function will be executed.

<view bindtap="handleTap">点击事件</view>
<view bind:tap="handleTap">另一种写法</view>


// pages/my/index.js
Page({
  handleTap(){
    console.log("执行了点击事件");
  }
})

        2. Prevent event bubbling : In addition to bind, event binding can also be done through catch in the mini program. Events bound through catch will not trigger event bubbling.

        3. Event capture : The triggering of events is divided into two stages, the first is the capture stage, and the second is the bubbling stage. By default, events are triggered in the bubbling phase. If you want the event to be triggered during the capture phase, you can bind the event through capture-bind

        4. Event parameter passing : When passing event parameters in a mini program, you cannot write parameters in parentheses like in traditional web projects. In the applet, the parameters required for the event need to be defined on the label through data-method.

<!-- data-参数名=’参数值’ -->
<view bindtap="handleTap" data-msg="我是事件的参数">点击事件</view>

        When each event callback is triggered, an event object will be received, through which the parameters passed by the route can be obtained.

handleTap(e){
console.log("执行了点击事件");
	// 通过currentTarget中的dataset属性可以获取时间参数
    console.log(e.currentTarget.dataset.msg);
}

11. Logical rendering and list rendering methods

        1. Logical rendering

        In WXML, use wx:if ="{ {condition}}" to determine whether the code block needs to be rendered.

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

        Use  wx:elif and wx:else to add an else block:     

<view wx:if="{
   
   {length > 5}}"> 1 </view>
<view wx:elif="{
   
   {length > 2}}"> 2 </view>
<view wx:else> 3 </view>

         Because wx:if is a control attribute, it needs to be added to a label. If you want to judge multiple component tags at once, you can use a <block/> tag to wrap multiple components, and use the wx:if control attribute on it.

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

        In addition, WeChat applet can also perform conditional rendering through the hidden attribute. wx:if will delete the corresponding DOM when the condition is not met. The hidden attribute performs conditional rendering by setting the display attribute to none.

<view hidden="{
   
   {condition}}">
隐藏
</view>

        2. List rendering

        Use the wx:for control property on a component to bind an array to repeatedly render the component using the data of each item in the array. By default, the subscript variable name of the current item in the array defaults to index, and the variable name of the current item in the array defaults to item .

<!-- array 是一个数组 -->
<view wx:for="{
   
   {array}}">
  {
   
   {index}}: {
   
   {item.name}}
</view>

        Use  wx:for-item to specify the variable name of the current element of the array, and use wx:for-index to specify the variable name of the current index of the array . (Need to customize when nested loops)

<view wx:for="{
   
   {array}}" wx:for-index="idx" wx:for-item="itemName">
  {
   
   {idx}}: {
   
   {itemName.name}}
</view>

        Note: Use wx:key to specify a unique identifier for an item in the list

        The value of wx:key is provided in two forms:

        (1) String, representing a certain property of the item in the array of the for loop. The value of the property needs to be the only string or number in the list and cannot be changed dynamically.

        (2) The reserved keyword  this represents the item itself in the for loop. This representation requires the item itself to be a unique string or number.

The benefit         of setting the key value : When the data changes trigger the rendering layer to re-render, the components with the key will be corrected. The framework will ensure that they are reordered rather than re-created to ensure that the components maintain their own state and improve the list. Rendering efficiency

12. The life cycle of App.js, the life cycle in the page, and the life cycle of components

        1.The life cycle of app.js

                onLaunch: When the mini program initialization is completed, onLaunch will be triggered (only triggered once globally)

                onShow: When the mini program starts or enters the foreground display from the background, onShow will be triggered.

                onHide: When the mini program enters the background from the foreground, onHide will be triggered.

                onError: When a script error occurs in the applet, or the API call fails, onError will be triggered with error information.

        2. Life cycle in page

                onLoad: life cycle function--listens for page loading, triggering earlier than onShow and onReady

                onReady: Life cycle function--listen to the completion of the initial rendering of the page

                onShow: life cycle function--listen to page display, trigger events earlier than onReady

                onHide: life cycle function--listen to page hiding

                onUnload: life cycle function--listen for page unloading

        3. Component life cycle

life cycle parameter describe Minimum version
created none Executed when the component instance is just created 1.6.3
attached none Executed when the component instance enters the page node tree 1.6.3
ready none Executed after the component is laid out in the view layer 1.6.3
moved none Executed when the component instance is moved to another location in the node tree 1.6.3
detached none Executed when a component instance is removed from the page node tree 1.6.3
error Object Error Executed whenever a component method throws an error 2.4.1

13. User interaction feedback methods (loading, wx.showToast, wx.showModal)

        1. Use the loading attribute of the button component to display a Loading in front of the button text.

        2.wx.showToast displays prompts (generally used in conjunction with wx.hideToast)

wx.showToast({
        title: '已发送',
        icon: 'success',
        duration: 1500
})

//例如点击显示提示,在请求成功后通过wx.hideToast关闭提示

wx.hideToast()

        3.wx.showModal modal dialog box

wx.showModal({

      title: '标题',

      content: '告知当前状态,信息和解决方法',

      confirmText: '主操作',

      cancelText: '次要操作',

      success: function(res) {

        if (res.confirm) {

          console.log('用户点击主操作')

        } else if (res.cancel) {

          console.log('用户点击次要操作')

        }

      }

    })

14. Local storage method in WeChat applet

(1) Synchronization

        1. Storage: wx.setStorageSync('list', {age:5})

        2. Get: wx.getStorageSync('list')

  //本地同步缓存

  syncSet(){

    console.log('这是同步缓存');

    wx.setStorageSync('sync', {content:'这是同步缓存'})

  },

  //本地同步获取

  syncGet(){

    console.log(wx.getStorageSync('sync'));

  },

(2) Asynchronous

        1.Storage: wx.setStorage({})

        2. Get: wx.getStorage({})

  //本地异步存储

  asyncSet(){

    wx.setStorage({

      key:'async',

      data:'这是异步存储的数据',

      success(){

        console.log('异步存储');

      }

    })

  },

  //本地异步获取

  asyncGet(){

    wx.getStorage({

      key:'async',

      success(res){

        console.log(res);

      }

    })

  },

15. Page jump between mini programs

1.wx.navigateTo
        retains the current page, can only open non-tabBar pages, and returns to this page when returning.

wx.navigateTo({   url: 'path address', })

2.wx.redirectTo
        closes and unloads the current page, and can only open non-tabBar pages.

wx.redirectTo({   url: 'path address' })

3.wx.switchTab
        closes all non-tabbar pages and can only open tabBar pages.

wx.switchTab({   url: 'path address' })

4.wx.reLaunch
        closes and unloads all pages and can open any page

wx.reLaunch({   url: 'path address' })

5.wx.navigateBack
        returns to the previous page. You can specify how many pages to return. If redirectTo is used, the closed page will not be returned.

wx.navigateBack({   delta: 2 //The number of pages returned. If delta is greater than the number of existing pages, return to the home page. })

6.navigator tag

The url address added to the navigator tag can jump to a non-tabBar page.
If you want to jump to the tabBar page, you can add an open-type='switchTab' and you can jump to the tabBar page, which is essentially equivalent to the wx.switchTab function.

16. Passing parameters on the mini program page

        1. Route jump parameter transfer

        Can routing jump parameters be passed? splicing parameters.

wx.switchTab({

      url: '../todolist/todolist?id=789',

   })

//或者navigator标签

<navigator url="../detail/detail?id=666">带参数去detail</navigator>  

        After jumping to the specified interface, you can get the routing jump parameters from the options parameter (itself an object) in the onLoad method of the page.

  onLoad(options) {

    console.log(options);

  },

        2. If you want to pass the data parameters in the tag, you can customize the attributes, obtain the parameters through e in the corresponding event, and then splice them into the event jump path.

 //wxml中

 <button bindtap="navigateTo" data-num="10">wx.navigateTo</button>

//js中

navigateTo(e){

    console.log(e.target.dataset.num);

    wx.navigateTo({

      url: '/pages/detail/detail?id=999&num='+e.target.dataset.num,

    })

  },

17. How to use and encapsulate wx.request

        1.Use of http (wx.request)

        url developer server interface address. Note that the domain name needs to be configured here (note that the project configuration and domain name information need to be changed, go to the web applet developer management, modify, and separate multiple ones by blocking (;)) data request
        parameter
        header sets the request header, which cannot be set in the header Referer, default header['content-type'] = 'application/json'
        method (uppercase required) Valid values: OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
        dataType json return packet content format, if set If it is json, it will try to do a JSON parsing success on the returned data
        and receive the callback function successfully returned by the developer service.
        fail The callback function that fails to call the interface
        complete The callback function that ends when the interface call is completed (will be executed if the call is successful or failed)

wx.request({

      url: 'https://showme.myhope365.com/api/cms/article/open/list',

      method: "POST",

      data: {

        pageNum: 1,

        pageSize: 10

      },

      header: {

        "content-type": "application/x-www-form-urlencoded"

      },

      success: res => {

        console.log(res.data.rows)

      }

})

        2. Encapsulation of http requests

        effect:

  • Add unified request configuration
  • You can add request interceptors and response interceptors, and add some common processing before requests and responses.
function request(options) {

  // 请求拦截器

  //  ...

  // 1. 加一些统一的参数,或者配置

  if (!options.url.startsWith("https://") && !options.url.startsWith("http://")) {

    options.url = "https://showme.myhope365.com" + options.url

  }

// 默认的请求头

  let header = {

    "content-type": "application/x-www-form-urlencoded",

  };

  if (options.header) {

    header = {

      ...header,

      ...options.header

    }

  }

  return new Promise((reslove, reject) => {

    // 调用接口

    wx.request({

      // 默认的配置

      // 加载传入的配置

      ...options,

      header,

      success(res) {

        // 响应拦截器,所有接口获取数据之前,都会先执行这里

        //  1. 统一的错误处理

        if (res.statusCode != 200) {

          wx.showToast({

            title: '服务器异常,请联系管理员',

          })

        }

        reslove(res)

      },

      fail(err) {

        reject(err)

      }

    })

  })

}

export function get(url, options = {}) {

  return request({

    url,

    ...options

  })

}

export function post(url, data, options = {}) {

  return request({

    url,

    data,

    method: "POST",

    ...options

  })

}

18. Use of components and slots in mini programs

(1) Use of components

        1. Create a new components folder

        2. Create a new folder to generate components

Component({
  /**

   * Component property list

   */

  properties: {
  },

  /**

   * Initial data of the component

   */

  data: {
  },

  /**

   * Component method list

   */

  methods: {
  }

})

        3. Add to the json file of the file you want to use

{

  "usingComponents": {

    "Component name":"Component path"

  }

}

(2) Use of slots

(1) Text written directly in the component will be placed in the default slot

(2) By default, there can only be one slot in the wxml of a component. When you need to use multiple slots, you can declare and enable them in the component js.

Component({   options: {     multipleSlots: true // Enable multiple slot support in the options when defining the component   },   properties: { /* ... */ },   methods: { /* ... */ } })





//In component

<slot name="before"></slot>

  <view>Here are the internal details of the component</view>

  <slot name="after"></slot>

 //Where to use

<son1>This is the text placed in the default slot

<!-- This part of the content will be placed at the location of the component <slot name="before">-->

  <view slot="before">Here is the content inserted into the component slot name="before"</view>

    <!-- This part of the content will be placed at the location of the component <slot name="after">-->

    <view slot="after">Here is the content inserted into the component slot name="after"</view>

</son1>

19. How to pass parameters between parent and child components

        1. Pass from parent to child: Add custom attributes to the child component tag used in the parent component, accept it through properties in the child component, and then use it in the child component.

//parent component

<son1 canshu='kaixuan' >This is the text placed in the default slot

<!-- This part of the content will be placed at the location of the component <slot name="before">-->

  <view slot="before">Here is the content inserted into the component slot name="before"</view>

    <!-- This part of the content will be placed at the location of the component <slot name="after">-->

    <view slot="after">Here is the content inserted into the component slot name="after"</view>

</son1>

//Subcomponent js

  properties: {

    canshu:{

      type:[Number,String],

      value:'default value'

    }

  },

//Subcomponent wxml

  <view style="color: red;"> 父传子 { {canshu}}</view>

       2. Pass from child to parent: Bind a method to the child component, write the method to the methods of the child component js, pass the parameters through this.triggerEvent, and then use bind: in the parent component to bind a self to the child component label. Define the event. The event type should be consistent with that in the child component. Write the event name casually, and then you can get and change the value of the parent component in the corresponding event of the parent component to use it.

(1) Bind a method to the subcomponent, write the method into the methods of the subcomponent js, and pass the parameters through this.triggerEvent

 methods: {

    //child father

    toFather(){

         this.triggerEvent('myevent','Data passed from son to father')

    },

  }

(2) Then use bind: in the parent component to bind a custom event to the sub-component label. The event type should be consistent with that in the sub-component, and the event name can be written casually.

<son1 bind:myevent='myevent' >This is the text placed in the default slot

<!-- This part of the content will be placed at the location of the component <slot name="before">-->

  <view slot="before">Here is the content inserted into the component slot name="before"</view>

    <!-- This part of the content will be placed at the location of the component <slot name="after">-->

    <view slot="after">Here is the content inserted into the component slot name="after"</view>

</son1>

(3) Then in the corresponding event of the parent component, you can get and change the value of the parent component to use

//Get the value passed from child to parent

  myevent(res){

      console.log(res);

      this.setData({

        fromSon:res.detail

      })

  },

  

//Use in parent component

<view>{ {fromSon}}</view>

20. How to use Behavior

        Behaviors registers a behavior and accepts a parameter of type Object

module.exports = Behavior({

  created(){

console.log(1111);

  },

})

         Introduced in the js of the component to be used

import Behavior from "../../behavior/behavior"

 

Component({

  behaviors:[Behavior], 

...

})

Note that the life cycle will all go through, but if the mix-in has the same name as the data in the component, the following will overwrite the above.

Override and combination rules for fields with the same name

Components and their references  behavior can contain fields with the same name. These fields are processed as follows:

  • If there are properties or methods with the same name:
    1. If the component itself has this property or method, the component's property or method will override  behavior the property or method of the same name;
    2. If the component itself does not have this property or method,  the behaviors later  behavior property or method defined in the component's field will override the earlier property or method with the same name;
    3. On the basis of 2, if there are nested references  behavior , the rule is: 引用者 behavior override  被引用的 behavior the property or method of the same name.
  • If there is a data field with the same name:
    • If data fields with the same name are all object types, objects will be merged;
    • In other cases, data will be overwritten, and the overwriting rules are:  引用者 behavior >  被引用的 behavior ,  靠后的 behavior >  靠前的 behavior. (The one with higher priority overrides the one with lower priority, and the largest one has the highest priority)
  • Lifecycle functions and observers will not cover each other, but will be called one by one at the corresponding trigger timing:
    • For different life cycle functions, follow the execution order of the component life cycle functions;
    • For the same kind of life cycle functions and the same field observers, follow the following rules:
      • behavior Prioritize execution over components;
      • 被引用的 behavior Priority over  引用者 behavior execution;
      • 靠前的 behavior Priority over  靠后的 behavior execution;
    • If the same one  behavior is referenced multiple times by a component, the lifecycle functions and observers it defines will not be executed repeatedly.

21. Use of WebSocket

For details, please see my separate article linked below:

(2 messages) The use of WebSocket_will eventually arrive, the blog - CSDN blog icon-default.png?t=M85Bhttps://blog.csdn.net/gkx19898993699/article/details/128023620?spm=1001.2014.3001.5502

Guess you like

Origin blog.csdn.net/gkx19898993699/article/details/128020256