Because my small program is built with MPVUE framework, so the following sample code will contain MPVUE syntax, for reference only, do not like spray.

  • The subcontract

    The applet can only support a project of 8M size at most. Sometimes the project is very large, so it needs to use subcontracting, and the subcontracting size cannot exceed 2M.

    "Pages ": [// This is the main package file "pages/home/main", "pages/login/main"], "subpackages": [// This is the subpackages file {"root": "pages/exam/", "name": "exam", "pages": [ "main", "examPaper/main", "exercise/main" ] } ]

    }

    Jump to the path of the subcontract is root + pages, such as wx. NavigateTo ({url: ‘/ pages/exam/examPaper/main’})

    Note that the pages with the bottom navigation bar (that is, the pages configured in the app.json tabBar) must be written in the main package

  • The life cycle

    I’m just going to briefly talk about some common scenarios for onLoad, onUnload, onShow, and onHide

    A. The applet enters the background from the foreground (i.e. the user clicks the upper right corner to exit the applet or presses the home button to leave WeChat) and triggers OnHide

    B. Triggers onShow and onHide when switching between pages in the bottom navigation bar (wx.switchTab)

    C. Using wx.navigateTo or wx.redirectTo toggle, page display triggers onLoad, onShow, leaving page triggers onUnload (does not trigger onHide)

    D. When switching from a normal page to a page with a navigation bar at the bottom using wx. SwitchTab, such as switching from the login page to the home page, the login page does not trigger life cycle, and the home page triggers onLoad, onShow

    E. When jumping from the parent interface to the child page, the parent page triggers OnHide, and the child interface triggers OnLoad and OnShow. When returned from the child page to the parent page, the child page onUnload, the parent page onShow

  • Route jump and pass parameter

    wx.navigateTo({ url: ‘/pages/logs/main? id=1’ })

    Obtain parameters: $root.$mp. Query. ID to jump from a normal page to a page with the bottom navigation bar is wx.switchTab, normal jump is wx.navigateTo (equivalent to this.$router. Wx. redirectTo (equivalent to this.$router. Replace in Vue), wx.navigateBack({delta: 1}) (equivalent to this.$router. Go (-1) in Vue))

  • Gets element node information

    wx.createSelectorQuery().select('#test').boundingClientRect((rect) => {
         console.log(rect)
       }).exec()
    
  • Pull down refresh pull up load

    To use the onPullDownRefresh and onReachBottom events, you need to do the following configuration in app.json

    "window": {
         "enablePullDownRefresh": true
       }
    

    onPullDownRefresh() {

    // doSomething wx.stopPullDownRefresh() // This is a good line to add to the page to prevent the page from reloading after a drop down

    },

    onReachBottom() {

    // dosomething

    } If you do not pull down to refresh and pull up to load, you can turn EnablePullDownRefresh off in the main.json configuration file of the current page

      {
         "enablePullDownRefresh": false
       }
    
  • Lazy image loading

    A. Use the default image instead of the image when the image is loaded wrong

    <img: SRC = 'image address' @error= 'errorImg' >

    errorImg(){

    // Replace the failed loading image with the default image

    }

B. lazy loading

Method one: use IntersectionObserver small program provides a IntersectionObserver API that can be used to monitor element and the intersection of the page To view WeChat related documents: https://developers.weixin.qq…

<div class='home' <div class='home' </div> </div> // <div class='home' onLoad() {const _observer = wx.createIntersectionObserver() _observer.relativeTo('.scroll-view') .observe('.home', (res) => {console.log(res. IntersectionRatio > 0) // If greater than 0, then intersect})} // Or onLoad() {const _observer = wx.createIntersectionObserver() _observer.relativeToViewport() .observe('.home', (res) => { console.log(res.intersectionRatio > 0) }) }

Method 2: Use onPageScroll

onPageScroll: throttle( function(e) { wx.createSelectorQuery().select('.home').boundingClientRect((ret) => { if (ret.top <= Wx.getSystemInSync ().windoWhEight) {// Check whether it is in display range // doSomething}}).exec()}, 100), throttle(Fn, Interval) {/ / throttling let enterTime = 0 / / trigger time const gapTime = interval | | / 300 / time interval, if you don't pass the interval, Return function() {const context = this const backTime = new Date() // return function() {const context = new Date() {fn. Call (context, arguments) enterTime = backTime}}
  • Dynamically change the text in the top navigation bar

    The title above the navigation bar is configured using main.json

    {

    "NavigationBartitleText ":" Home page"

    }

    Sometimes the same page will have different titles according to the content of the page, this time you need to configure the navigation bar title name dynamically



    wx.setNavigationBarTitle({

     title: title

    })

    Sometimes you want the entire page to fill the screen with no navigation text, as shown in the image above. This can be configured in the main.json of the current page

    {
      "navigationStyle": "custom"
    }
    
  • Textarea style penetration

Small program textare in the Z -index hierarchy is the highest, any element can not be covered. Here is the idea, I will not post the code. Make a div that looks like the current textarea (cloned div for short) and display the content of the textarea inside the div. When the dialog box pops up, the textarea is hidden and the cloned div is displayed. When the dialog box closes, the textarea is displayed and the cloned div is hidden

  • When you scroll the pop-up layer, the content below the pop-up layer also scrolls

    One, change the value of scroll minus y

    <scroll-view :scroll-y=”scrollY”>

    ScrollY =false now scrollY=true when the popup layer is closed catchtouchmove=”return”

  • Keyboard pops up

    Have an action bar page below, when the keyboard pop-up, the action bar above to locate the keyboard, to use the program at this time of an event, this is a small program documents screenshots https://developers.weixin.qq…



    Reference to writing:

    <textarea @keyboardheightchange="keyboardheightchange"</textarea> <div class="bottom-content" :style="{bottom: Bottom + 'px'}"> </div> KeyboardheightChange (val) {this.bottom = val.target.height} focus(val) {// You can also use focus with blur this.bottom = val.target.height } blur() { this.bottom = 0 }
  • WX-Parse is a plug-in for parsing HTML. If you have an image, click on the image to preview it

    https://github.com/icindy/wxP…

  • forwarding

    onShareAppMessage: function(res) {
         return {
           title: '',
           path: '/pages/home/main',
           success: function(res) {
           },
           fail: function(res) {
           }
         }
       }
    
  • To upload pictures

    wx.chooseImage({

    SizeType: ['original', 'Compressed ']; // SizeType: ['original',' Compressed ']; ['album', 'camera'], // You can specify whether the source is an album or a camera. By default, both have success: (chooseImageRes) => { const tempFilePaths = chooseImageRes.tempFilePaths[0] wx.uploadFile({ url: url, filePath: tempFilePaths, name: 'fileData', header: { 'Content-Type': 'multipart/form-data' }, formData: { method: 'POST' }, success: (res) => { //dosomething } }) }

    })

  • The preview image

    wx.previewImage({

    Urls: [imgSrc] // A list of images to preview HTTP links

    })

  • Preview PDF Document

    wx.downloadFile({

    url: url, success(res) { wx.openDocument({ filePath: Res.tempFilePath, success(res) {}, fail() {console.log(' This document cannot be opened because the type is not supported or is corrupt ')}})}

    })

  • scan the code

If scanning is to open a web page, you can make a separate page with only WebView, jump to this page, and pass in the URL

Wx. scanCode({onlyFromCamera: false, scanType: ['qrCode', 'barCode'], // function(res) { const resultStr = res.result if (resultStr.indexOf('https') === 0) { wx.navigateTo({ url: `/pages/home/webView/main? Url =${resultStr} '}) // jump to webview page} else {// doSomething}}) <div> <web-view: SRC ="url"></web-view> // Url gets </div> via onLoad(){this.url = this.$root.$mp