[TOC]

Memo for personal use to be completed

basis

Differences from browser development

  • The JS engine and rendering engine are not mutually exclusive
  • No DOM BOM related apis are included

grammar

WXML

  • Data binding

    {{message}}


  • {{item}}

  • Conditions apply colours to a drawing

    <view wx:if="{{view == 'WEBVIEW'}}"> WEBVIEW </view>
    <view wx:elif="{{view == 'APP'}}"> APP </view>
    <view wx:else="{{view == 'MINA'}}"> MINA </view>
    Copy the code
  • template

    <template name="staffName">
      <view>
        FirstName: {{firstName}}, LastName: {{lastName}}
      </view>
    </template>
    
    <template is="staffName" data="{{... staffA}}"></template>
    <template is="staffName" data="{{... staffB}}"></template>
    <template is="staffName" data="{{... staffC}}"></template>
    Copy the code

WXSS

  • The unit is RPX. The default screen width is 750rpx
  • External style import, @import
  • Inline style<view style="color:{{color}};" / >.
  • Supported selector ID selector class selector element selector ::before ::after
  • For animations, you can use CSS gradients and CSS animations
  • Using JS to create animations,this.animate(selector, keyframes, duration, callback)To removethis.clearAnimation(selector, options, callback)
  • Based on scrolling driven animation,this.animate(selector, keyframes, duration, ScrollTimeline)

WXS

  • Ios rendering performance is high, andriod rendering performance and JS basically the same
  • Write JS in WXML,<wxs module="wxs" src="./test.wxs"></wxs>

The life cycle

Page life cycle

  • Execute after the onLoad page is created
  • The onReady page is executed after rendering
  • OnUnload before the page is unloaded
  • The onShow page appears in the foreground for execution
  • Executed when the onHide page changes from foreground to background
  • OnPullDownRefresh This command is executed when the drop-down refresh is triggered
  • OnReachBottom executes when it hits bottom
  • OnPageScroll is executed while the page is scrolling
  • OnResize Executed when the page size changes
  • OnTabItem TAB executes when clicked
  • OnShareAppMessage is executed when the page is shared by the user
  • .

Global life cycle

  • OnLaunch // Trigger after applets are loaded

How do Js threads and render threads work together?

  1. Js thread created render thread init
  2. The Js thread triggers onLoad onShow in turn and waits for notify notification from the rendering thread
  3. The Js thread sends initialization data to the render engine after receiving notify notification from the render thread
  4. The render thread receives the initialization data, starts the first rendering, and notifies the Js thread when the rendering is complete
  5. The Js thread receives the message that the rendering is complete and fires the onReady event
  6. When the data is updated, the Js thread notifies the renderer thread to render
  7. The onHide event is emitted when a page is hidden in the background
  8. The onShow event is emitted when a page is unmasked from the background and displayed in the foreground
  9. An onUnload event is fired when the page is closed or destroyed

routing

The page stack

  • GetCurrentPages () gets the current page stack
  • NavigateTo new page is pushed
  • NavigateBack currently unstacks the page
  • RedirectTo The current page is unloaded and the new page is unloaded
  • All switchTab pages are removed from the stack, leaving only new TAB pages
  • All reLaunch pages are off the stack, leaving only new pages

Pay attention to the point

  • NavigateTo and redirectTo can only jump between non-Tabbar pages
  • ReLaunch can open any page
  • SwitchTab Opens only tabBar pages
  • The route parameters are obtained from onLoad on the page

The event

  • Event bind bindtap, bind:tap

  • Bubbling. The bind method supports bubbling by default, and the catch binding prevents events from bubbling

  • Capture, capture-bind, capture-catch

  • Mut-bind is only triggered once during the bubbling/capturing process, and is mutually exclusive with the mut-bind method on the parent/child component

  • Dynamic binding

    <view bindtap="{{ handlerName }}">
        Click here!
    </view>// handlerName is obtained by this.data.handlerName, which must be a string specifying the event handlerNameCopy the code

Event source object

  • CustomEvent TouchEvent inherits from BaseEvent
  • Target The source object fired by the event, the component of the currentTarget event binding, commonly seen in event delegates
  • Target and currentTarget can obtain custom attributes of corresponding components from dataset
  • Detail Data carried by a custom event
  • A MARK differs from a dataset in that it can retrieve a custom mark value for a series of components that have been bubbled/captured

data

Two-way binding

  • <input value="{{value}}" />  <input model:value="{{value}}" />
    Copy the code
  • Bidirectional binding delivery of custom components

    // custom-component.js
    Component({
      properties: {
        myValue: String}})Copy the code
    <! -- custom-component.wxml -->
    <input model:value="{{myValue}}" />
    Copy the code

    use

    <custom-component model:my-value="{{pageValue}}" />
    Copy the code

Data is stored

  • Each wechat applet can have its own local cache, By wx. SetStorage/wx. SetStorageSync, wx. GetStorage/wx getStorageSync, wx. ClearStorage/wx. ClearStorageSync, Wx. RemoveStorage/wx. RemoveStorageSync for literacy and clean up the local cache.
  • For the same wechat user, the upper limit of a small program storage is 10MB.
  • The local cache is cleaned just as the code package is cleaned. The local cache is cleaned only when the code package is cleaned.

Obtaining Node Information

  • const query = wx.createSelectorQuery()
    Copy the code
  • Node layout intersection status

    wx.createIntersectionObserver().relativeToViewport().observe('.target-class'.(res) = > {
          res.id // Target node ID
          res.dataset // The target node dataset
          res.intersectionRatio // The ratio of the intersection area to the layout area of the target node
          res.intersectionRect // The intersection area
          res.intersectionRect.left // The left boundary coordinates of the intersection area
          res.intersectionRect.top // The upper boundary coordinates of the intersecting regions
          res.intersectionRect.width // The width of the intersecting area
          res.intersectionRect.height // The height of the intersection area
        })
    Copy the code

Making a Network request

  • The options include ordinary HTTPS request (wx.request), uploadFile (wx.uploadfile), downloadFile (wx.downloadfile), and WebSocket communication (wx.connectsocket). Since 2.7.0, UDP communication is provided (wx.createudpsocket)
  • The timeout period can be inapp.jsongame.jsonThrough thenetworktimeoutConfiguration. The default is 60 seconds.
  • Network-requestedrefererHeader cannot be set.
  • Wx. request, wx.uploadFile, and wx.downloadFile have a maximum of 10 concurrent requests.
  • The maximum concurrency limit for wx.connectSocket is 5.
  • Small program into the background after running, if5sThe internal network request is not completed and an error message will be called backfail interrupted; The network request interface call will not be called until it comes back to the foreground.
  • It is recommended that the server return value be utF-8 encoded. For non-UTF-8 encodings, the applet will try to convert, but the conversion may fail.
  • The applet automatically filters the BOM (only one BOM).
  • As long as the server successfully receives the return, regardlessstatusCodeWhatever it is, it goes insuccessThe callback. Please judge the return value according to the business logic.

features

modular

  • Imports exports via module.exports and require

scope

  • Each file is a separate scope
  • You can define global variables in app.js and get them using the getApp().xx method

API

  • The event listening API starts with ON
  • An API that ends with sync is a synchronization API
  • Most asynchronous apis accept an object as a parameter that contains success, fail, complete, and other parameters defined by the interface. When not passed, the mini-program defaults to returning a Promise object from version 2.10.2
  • Arguments to the callback function, errorMsg (returns OK on success), errorCode (returns 0 on success), and other data returned by the interface
  • Wx.cloud.callfunction () calls the cloud function

The development of

Development of file

  • Separate configuration files page.json, entire configuration files app.json, tool configuration files project.config.json, sitemap.json are used to configure whether pages can be indexed
  • .wxml is used to write HTML
  • . WXSS Is used to write CSS
  • Unlike javascript, WXS is a scripting language for small programs. Projects with high performance requirements are preferred
  • .js is used to render.wxml

Built-in API

  • Get the geographical location wx.getLocation
  • Scan wx. ScanCode

Data method sharing

  • Pages can cite behaviors. Behaviors can be used to make multiple pages have the same data fields and methods

Custom TabBar

  • inapp.jsonIn thetabBarSpecified in itemcustomField, while the resttabBarRelated configurations are complete.
  • All TAB pages must be declared in JSONusingComponentsTerm, can also be inapp.jsonEnable globally.
  • Add the tabBar code file. Add an entry file to the root directory :custom-tab-bar/index.js(.json.wxml.wxss)

Custom Components

Component slot

  • MultipleSlots: true for multipleSlots. Name =’a’. The parent component passes slot=’a’.

Component style

  • Style constraint, using class selectors, not descendant selectors

  • Style isolation

    • Options Open styleIsolation: ‘Isolated ‘/ ‘apply-shared’
    • 2.10.1 Above, styleIsolation: ‘Isolated’ can be configured in json files of custom components
    • 2.2.3 Above, inComponentoptionsSet in theaddGlobalClass: true, indicating that the WXSS style of the page can affect custom components
  • External styles are passed in, and several external style classes are defined in the Component using the externalClasses definition section

    Component({
      externalClasses: ['my-class']})Copy the code
  • When virtualHost: true is set in options, the custom component does not expect the node itself to be able to set styles, respond to Flex layouts, etc. Instead, it expects the layer 1 node within the custom component to respond to Flex layouts or styles entirely determined by the custom component itself

Component constructor

  • You can define components
  • You can define pages by configuring page page.json’s “usingComponents”: {}. Properties is used to receive the routing parameters of the page, and methods is used to define the lifecycle methods of the page
  • Benefits. You can use Behaviors to extract common code across multiple pages

Parent-child component communication

  • Parent component accesses child component,this.selectComponent(selector)Method to get the child component instance object. If you need to customize the return data of the selectComponent, use built-inbehavior: wx://component-exportWith custom componentsexportThe definition section will be used to specify the component to beselectComponentThe return value when called
  • This. TriggerEvent (‘myevent’, myEventDetail, myEventOption)

The life cycle

  • Created. Normally, this lifecycle should only be used for componentsthisAdd some custom property fields.It cannot be called at this timesetData
  • Attached. Triggered when the component is fully initialized and the page node tree is entered. Most of the initialization work can be done at this point
  • Detached. After a component leaves the page node tree or exits a page while the component fires in the page node tree
  • Define the way
    • The first level parameter is defined as heavy
    • Defined in LifeTimes
  • The life cycle of the page on which the component is located, inpageLifetimesDefinition in the definition section

behaviors

  • It can contain a set of properties, data, lifecycle functions, and methods
  • When a component references it, its properties, data, and methods are merged into the component, and lifecycle functions are called at the appropriate time
  • Components can reference multiple behaviors
  • Custom components can be made by referencing the built-inbehaviorTo get some behavior of the built-in component

Relationships between components

  • Define relations: {PATH, {type, linked, linkChanged, unlinked, target}} fields.

The listener

  • Observes: {propName: function () {}}. Used to listen for changes to properties in data

Pure data field

  • Data fields that do not participate in rendering can be passedoptionsSpecified in the definition sectionpureDataPatternIs a regular expression. Fields whose field names match the regular expression become pure data fields
  • You can render the interface using pau to listen for changes in pure data fields

Abstract the node

  • Dynamically determine which nodes are referenced within a custom component. Needs to be declared in componentGenerics:

    <! -- component.wxml -->
    <view wx:for="{{labels}}">
      <label>
        <xxx></xxx>
        {{item}}
      </label>
    </view>
    Copy the code
    // component.json
    {
      "componentGenerics": {
        "xxx": true}}Copy the code

    Use

  • Setting the Default node

    {
      "componentGenerics": {
        "selectable": {
          "default": "path/to/default/component"}}}Copy the code
  • In the generic reference of the node generic: XXX =” YYy “, the value YYy can only be a static value and cannot contain data binding. Therefore, the abstract node feature is not suitable for scenarios where node names are determined dynamically.

Custom component extension

  • Behavior()The constructor provides a new definition sectiondefinitionFilterFor supporting custom component extensions
  • definitionFilterIs a function that is called with two arguments. The first argument is the definition object of the component/behavior that uses the behavior, and the second argument is the behavior that uses the behaviordefinitionFilterFunction list

The plug-in USES

  • inapp.jsonTo declare the plug-in you want to use
  • If the plug-in is only used in one subcontract, you can place the plug-in in that subcontract only. If the base library version is earlier than 2.9.0, you cannot jump to the plug-in page in the subcontract directly from the page outside the subcontract. Instead, you need to jump to the non-plug-in page in the subcontract first and then to the plug-in page in the same subcontract
  • Use custom components provided by plug-ins, andUse normal custom componentsIn a similar way. injsonThis file is used when defining custom components that need to be importedplugin://The protocol specifies the plug-in reference name and custom component name
  • When you need to jump to the plug-in page,urluseplugin://A prefix in the form ofplugin://PLUGIN_NAME/PLUGIN_PAGE
  • Can be used when using the plug-in’s JS interfacerequirePluginMethods.

Operating local files

  • Wx.getfilesystemmanager () is used to obtain a globally unique FileSystemManager. All file system management operations are invoked using FileSystemManager
  • Local temporary files (such as tempFilePaths) will be retrieved at any time, regardless of size. Local cache file/local user file, cannot/can be customized directory, the two together can store up to 200M

The code of the subcontract

  • The whole small program all subcontracting size is not more than 20M
  • The size of a single subcontract/main package cannot exceed 2M
  • Through theapp.jsonthesubpackagesTo define subcontracting. Defined in the corresponding subcontract configuration itemindependentThe subcontracting corresponding to the field declaration is independent subcontracting
    • Plugins are not currently supported in standalone subcontracting.
    • AppCan only be defined in the main package, not in independent subcontractingApp, can cause unexpected behavior;
    • Independent subcontracting cannot rely on the contents of the main package and other subcontracting
  • In order to avoid the situation that the main package cannot be obtained when getApp is obtained in the subcontract (the subcontract may not load the main package). You can set getApp({allowDefault: true}) to return a default implementation
  • inapp.jsonincreasepreloadRuleConfigure to control the preloading of subcontracts

adapter

  • Configures “pageOrientation”: “Auto” to app.json/page.json

  • IPad configuration screen rotation, app.json “resizable”: true

  • Listen to screen rotation, page onResize, custom component pageLifetimes:{resize}, wx.onWindowreSize

  • Media queries

    .my-class {
      width: 40px;
    }
    
    @media (min-width: 480px) {
      /* Style rules that only work on 480px or wider screens */
      .my-class {
        width: 200px; }}Copy the code

production

Scene: the value

  • Can be found inApponLaunchonShowOr,wx.getLaunchOptionsSyncTo obtain the values of the above scenarios
  • Access to source

User experience optimization

  • Using the initial render cache, the page page is configured with “initialRenderingCache”: “static”, global configuration, app.json window configuration, “initialRenderingCache”: “static”
  • Adding dynamic content, initial render cache “initialRenderingCache” : “dynamic”, at the same time in the page calls this. SetInitialRenderingCache (dynamicData)
  • Disable the initial rendering cache way, enclosing setInitialRenderingCache (null)

Small program start

  • Cold boot (reload boot) and hot boot (from background to foreground)
  • The reason for the applets being destroyed is that the user has been waking up the applets for a long time and the applets system is consuming too much resources (via wx.onmemoryWarning)
  • Launch strategy
    • Scenario A: Cold startup, restart policy is followed, the home page or the last page may be displayed. Hot boot, return to previously viewed page
    • Scenario B, reLaunch to the specified page each time it is opened
  • In the corresponding JSON file of the page (or globally in the window section of app.json)restartStrategyConfiguration items can change this default behavior
  • You can save the state on the page when you exit, through the page’s onSaveExitState

Applets update mechanism

  • The new version information cannot be updated all the time. The latest version information should be sent to users within 24 hours after it is sent
  • On a cold start, this is handled through the WX.getupDatemanager API

other

Worker

  • In data transmission between Worker and main thread, both parties use worker.postmessage () to send data, and worker.onmessage () to receive data. The transmitted data is not directly shared, but copied.