Small program development considerations

Posted by WanamakerMedia on Thu, 27 Jan 2022 09:08:40 +0100

1. The block tag is not rendered on the page, but contains elements. Usage: collective explicit and implicit
2. Directly modify this of the Page instance Data without calling this SetData # cannot change the state of the Page, and it will also cause data inconsistency.
3. Since setData is some communication consumption that requires two threads, in order to improve performance, the data set each time should not exceed 1024kB.
4. Do not set the value of any item in the data to undefined, otherwise some unexpected bug s may be caused.
5. Variables can be directly interpolated anywhere in the applet, and true in the applet also needs to be interpolated, such as {true} {false}}
6. wx:for is directly equal to the variable to realize the cycle. Usage: wx:for = '{items}}', the item is automatically generated internally, which can be used directly, or the default index and item can be modified through wx:for index and wx:for item
7. When creating a new page, in app After entering the page path in JSON, the compiled project will automatically generate the page and the corresponding file
8. Wechat applet wxml does not support literal objects, but supports literal arrays. Objects can be written in the form of arrays: Data extra = "{{[{unittype: 'specs', index: index}]}"
9. When creating a custom component, you need to add code in the json file: "component": true; Suppose a method called customeMethod is defined in the custom component, which can be used in the page through this myComponent = this. Selectcomponent ('#mycomponent') first gets the component instance object, and then you can use this myComponent. Custommethod calls the method in the component.
10. How to set the bottom of the button on the scroll view page? Set the height Calc (the height of 100vh button) for the scroll view and hide the excess part. Then use the flex layout for the scroll view and button. Note that the top element should not use margin, otherwise the margin will collapse, causing the page content to slide before one screen.
11. Component listening events: observers, which can listen to data and properties data; The page does not listen to events, and there is no calculation attribute and filter function in the applet. wxs implementation can be considered. The functions in wxs can be written in {}}, for example: {getData()}} instead of calculation attribute and filter function. However, wxs has many function limitations. For example, if you don't know let, you can only var; For example, you can't use the includes of the array. You can only use the simplest for loop; wait.
12. Slot usage
Sub component: < slot name = "name" > < / slot >
Parent component: < view slot = "name" > < / View >
13. Set and get global variables

var app = getApp();
app.globalData.iBeaconInfo; // obtain
app.globalData.iBeaconInfo = value; // set up

14. The small program calculates the safe area inset bottom (Env), which is mainly aimed at the bangs and bottom horizontal bars of IOS, which may cover the buttons and other contents
15. The picker view multi column date component has the problem of initial default value assignment. The main reason is that the component renders too many elements, resulting in the assignment of value before the element is rendered. If the corresponding data is not found, the wrong data will be displayed. Solution: ensure that the value is assigned after the rendering of the picker view column data. For example, use setTimeout(function,0) to assign the value after the execution of the main thread.
16. background:url() cannot be used in applet to introduce local background image, otherwise it cannot be displayed. Solution: 1. You can refer to the network image, that is, the full path image (with http or https path). 2. You can also convert the picture to base64 bit encoding.
17. If the src of the image on the page is a static value, there is no problem. If you dynamically assign a value to him through js, you can't directly give a relative path, otherwise you can't display the picture. The path to import the picture is obtained in js, so if it is a relative path, you need to add require('picture path ') in js code to obtain the picture reference, and then assign it to the src attribute of image.
18. Configuration file sitemap JSON configures whether the applet and its page are allowed to be indexed by wechat
19. Data transmission
1) Data can be transferred between parent and child components or parent page sub components through properties and this Trigger event ('input focus', value):
Parent component transfer data:

<formInputItem
prefix="Tangkou name"
prefix-class="proof-item-prefix requrie"
input-value="{{pondDetail.pondName}}"
data-field="pondName"
bind:input-change="handleInputChange"
bind:input-blur="handleInputChange"
placeholder="Please fill in the name of Tangkou"
input-type="text"
>
</formInputItem>

Data received by sub components:

properties: {
  // Note above input box
  formLabel: {
  type: String,
  value: ''
  },
  // Input box prefix
  prefix: {
  type: String,
  value: ''
  },
}

The child component modifies the parent component data by calling the parent component method:

handleInputFocus(e) {
     let { value } = e.detail
     let { inputName } = this.data
     this.triggerEvent('input-change, { name: inputName })
}

The parent component is called by the child component to modify the data:

handleInputChange(e){
    let { field } = e.target.dataset;
    let { value } = e.detail;
    this.setData({
      [`pondDetail.${field}`]: value,
  })
}

2) If data is transferred between parent and child pages:
The parent page passes data through the Url parameter, and sets the method of modifying data called by the child page through events:

wx.navigateTo({
        url: `/pages/home/pondFodderModel/pondFodderModel?modelId=${this.data.modelId}&modelName=${this.data.modelName}`,
        events: {
          setModel: (data) => {
            this.setData({
              'modelId': data.id,
              'modelName': data.name
            })
          }
        }
})

Modify parent page data for child pages:

const eventChannel = this.getOpenerEventChannel()
eventChannel.emit('setModel',{id,name})

20. Wechat applet page is not allowed to use object Values and other similar functions to traverse the object, so you can use the following methods to traverse the object on the page:

//wxml 
<view wx:for="{{obj}}" wx:for-index="key" wx:for-item="value"> 
  {{key}} : {{value.address}} 
</view> 
//js 
data:{ 
  obj: {...} 
}

It can also be implemented through wxs files
21. Some special functions of the input input box: control the button text in the lower right corner of the keyboard through the confirm type value, input keyboard enter event bindconfirm, turn on the keyboard auto focus, etc.
22. When many built-in interfaces of wechat are used in webview, the address of webview must use the real domain name (avoid using local IP and localhost), and must be debugged by the real machine.
23. Wechat applet webview can send messages to the applet through Wx miniProgram. PostMessage, and then bind bindmessage on webview to specify the listening event.

<web-view
  src="{{url}}"
  bindmessage="handlePostMessage"
></web-view>

24. Session and storage are not shared between webview and applet. Each page of webview is nested in an applet. If you need to jump to a page through an applet, each webview does not share a session, but can share localStorage and is permanently cached locally. If you do not need to jump through the applet, the session can also be shared.
25. Wechat applet calls Wx The request will return a requestTask object. Calling the abort method of the requestTask object will interrupt the request, for example, const task = Wx request(); task. abort(). cancelToken can be used for axios interrupt request in vue. Please refer to relevant articles for specific usage.
26. Determine whether the child component can scroll by judging whether the parent component scrolls to the bottom. The implementation method is as follows: the built-in methods bindscrolltoupper and bindscrolltower of scroll view are inaccurate and will cause errors. You can only judge whether the scroll view scrolls to the bottom by binding bindscroll="scrollChild" event to scroll view, The specific implementation code is as follows: (at the same time, there are the following problems: there is an error of 0.3 when vivo mobile phone judges whether the scroll view scrolls to the bottom. The following code has fixed the problem)

scrollChild(e){
  this.otherData.scrollTimer && clearTimeout(this.otherData.scrollTimer);
  this.otherData.scrollTimer = setTimeout(() => {
    let query = wx.createSelectorQuery().in(this)
    query.select('#detailWrap').boundingClientRect((res) => {
      // 0.5 is because the vivo mobile phone has an error equal to about 0.3
      if(res.top>0.5){
        this.setData({
          childScroll: false,
        })
      } else {
        this.setData({
          childScroll: true,
        })
      }
    }).exec()
  },40)
},

27. Use of Storage

this.setStorageSync('key', value)
let value=wx.getStorageSync('key')

28. Set the title at the top of the applet

wx.setNavigationBarTitle({
  title: shopname //Page switching, changing page title
})

29. App cannot be used in applet components by default Global style of wxss
You can add the addGlobalClass attribute to the js file of the component

Component({
  options: {
    addGlobalClass: true
  }
})

Topics: Mini Program