Wechat applets

Introduction to wechat mini program (click)
Applets are a new open capability that allows developers to develop applets quickly. Small programs can be easily obtained and spread in wechat, and have excellent use experience. Features of wechat mini program: no installation, operation more similar to the original APP, must be used in wechat open registration scope: individuals, enterprises, governments, media, other organizations. Wechat applet and wechat's native function applications are essentially the same -- they are both Web apps. Web App is a mobile phone App form that is realized through H5 page technology and has almost the same function and interface as Native App.
Advantages of wechat applets (click)
1. Wechat has a large number of users with high stickiness, so it is easier to develop products in wechat to reach users; 2. The cost of promoting App or public account is too high. 3. Low cost of development adaptation. 4. It's easy to make small trials and errors and then iterate quickly. 5. Cross-platform.
Advantages of wechat mini program for entrepreneurs (click)
1. The sharp rise of App traffic cost 2. The mobile Internet pattern has been basically determined, and the main demand scenarios of users have been controlled by giants 3. Competition for user time for all products
Mini-program publicity (click)
- Small program search entrance & nearby small program - scan, long press to identify small program code - friends sharing, group sharing - associated public number - third party small program application store - jump between small programs
Applets development process (click)
1. Register the mini program on wechat public platform. After registration, information can be improved and developed synchronously. 2. Mini program Information Complete the basic information of the mini program, including the name, profile picture, introduction, and service scope. 3. Develop small programs After binding small program developers and configuring development information, developers can download developer tools and refer to development documents for development and debugging of small programs. After completing the development of the small program, submit the code to the wechat team for review. After passing the review, it can be released (it cannot be released during the public test).
Wechat mini program registration (click)
- through the public number registration (to avoid repeated certification) (do not support the individual type of public number reuse qualification to create small procedures). - enter/WeChat applet's official website (https://mp.weixin.qq.com/wxopen/waregister?action=step1) registered. (visit the registration page (https://mp.weixin.qq.com/cgi-bin/registermidpage?action=index&lang=zh_CN&token=), · Individual subject cannot complete payment, card package, search nearby applet function. · Only one small program can be applied for by one mailbox for registration. · Email addresses that have registered public accounts, development platforms, enterprise accounts and bound personal accounts cannot be used. · Information accuracy shall be guaranteed during data improvement. Once the main information is filled in, it cannot be modified. · When uploading the basic information of the enterprise, signature and official seal are required to ensure the clarity of the picture; otherwise, the audit will not be passed. · Enterprises that have applied for wechat public accounts can directly click the mini program on the home page to enter the next step.
Use of wechat developer tools (click)
Create a new Project You can create a small program project locally when you meet the following criteria: 1. Need a small program AppID; If you do not have an AppID, you can choose to apply for a test number. 2. The login wechat account must be the developer of the AppID; 3. Select an empty directory or the non-empty directory exists in app.json or project.config.json. When you select an empty directory, you can choose whether to build a simple project under that directory. | project tools support additional open multiple items at the same time, every time when they open the project from the new window opens, entry has the following kinds: 1. Open the project from the project selection page, in the project window can be from the menu bar of the Project -> View all projects open the project selection page 2. Items opened from the menu bar's recently opened items list will now open in a new window. 3. The command line or HTTP call tools | open project management project To delete and batch delete local projects. | main interface developer tools main interface, from top to bottom, from left to right, are: the menu bar, toolbar, simulator, a directory tree, editing area, the debugger Six parts.| in the menu bar - switching accounts - about - check the update - developers BBS (https://developers.weixin.qq.com/community/develop/mixflow) - / developer documentation (https://developers.weixin.qq.com/miniprogram/dev/framework/) - debugging - change the development mode: quickly switch the public - web debugging and small program debugging, to launch new project - | project Open recently - check all items - close the current project | file - new file - save - save all - close the file | editor: can view the edit related operations and shortcuts | tools - compile: compile the small program - the refresh of the project: Consistent with the compilation function, the corresponding shortcut CTRL (⌘) + R is reserved for historical reasons. Configuration: Can choose normal compilation or custom compilation conditions. - Front and background switching: simulates the operation of a client applet to run in the background and return to the foreground. Remove file caching, data caching, and authorization data | interface: main interface window control module of show and hide | Settings: - appearance Settings: control the editor's theme, font, size, color, space - edit Settings: the behavior of the control file, the editor's performance - proxy Settings: Select the directly connected network, system and manually agents - notification Settings: set whether to accept a certain type of notice | toolbars Click the user avatar can open individual center, here can be convenient to switch the user and view the developer tools received message. In the middle of the toolbar, you can select normal compilation or create and select custom conditions for compilation and preview. By cutting the background button, you can simulate the situation when a small program enters the background and the toolbar provides a quick entry to clear the cache. It can be convenient to clear the file cache, data cache, and background authorization data on the tool, convenient developer debugging. Toolbar on the right side is to develop the area of auxiliary functions, you can upload here | simulator code, version management, view the project details the status bar at the bottom of the simulator, you can see the current running applet visually scene value, Page path and parameter | independent window Click on the emulator/debugger In the top right corner of the button can be used to separate window display simulator/debugger | project card details - basic information This includes ICONS, appids, third-party platform names (only third-party development applets are displayed), directory information, the last time the code was submitted, and the size of the code package. - Local Settings Developers can select any base library version here to develop and debug compatibility issues with older versions. - project configuration | project setup code protection mainly to flatter the file and replace the require reference file name, one of the following is not suitable for using this function. If a small program has only a simple page, this function is not effective. 2. If a file exceeds 500KB and requires a file in the project, the file may not be found. Var a = 'somefile.js'; require(a); Var a = require; var a = require; a('somefile.js'); 5. Require as an argument to a binary operator, such as require + 1; 6. Use... Request domain name and TLS version Domain name Details/Item Configuration Displays the security domain name information of the applet. The legitimate domain name can be set in the MP management background. | set appearance Settings - themes - the debugger theme - font size - space simulator position edit Settings - file - editor - size proxy Settings Tab Can be configured without the use of agent, agent or use the system, or the use of custom agent. Security Settings can be turned on and off the CLI/HTTP invocation function | code to edit the file format For iOS only supports the UTF8 encoding format, the latest version of developer tools will be in the upload code when checking the code file for a coding format. The file support tool currently provides five types of file editing: WXML, WXSS, JS, JSON, WXS and image file preview. You can create a Page in either of the following ways: 1. Right-click in the directory tree and choose New Page. The WXML, WXSS, JS, and JSON files required for the Page are automatically generated. In the pages field of app.json, add the path of the page to be created, and the required files for the page will be automatically generated

Wechat small program project

Project directory structure

Demo | - / pages | - / index | - index. Js/logical file/page | - index. Json/profile/page | - index. WXML / / page template file | - index. WXSS / / page style file | - / utils | - utils. Js | - app. Js / / small program global configuration file | - app. Json | - app. WXSS / / global style | - project. Config. | - json / / project configuration file sitemap.json

Applets file structure compared to the traditional Web

structure Traditional web Wechat applets
structure HTML WXML
style CSS WXSS
logic JavaScript JavaScript
configuration There is no JSON

Applets host environment

The environment provided by wechat client for small programs is the host environment.

The framework

The whole small program framework system is divided into two parts: logic layer (App Service) and View layer (View). WXML templates and WXSS styles are responsible for the view layer, while JS scripts are responsible for the logic layer.

The rendering layer and logic layer of the small program are managed by two threads respectively: the interface of the rendering layer uses WebView to render; The logic layer uses JsCore thread to run JS script.

A small program has multiple interfaces, so there are multiple WebView threads in the rendering layer. The communication of the two threads will be transferred through the wechat client (Native will also be used to refer to the wechat client below), and the network requests sent by the logic layer will also be forwarded through Native.

For detailed documentation on the rendering layer and logic layer, refer to the Applets framework

Programs and Pages

Before opening the mini program, the wechat client will download the code package of the entire mini program to the local. Next, you can know all the page paths of your current applet through the pages field of app.json: so the wechat client will load the code of the home page, and through some mechanism of the applet bottom, you can render the home page. After the applet is launched, the onLaunch callback for the app instance defined in app.js will be executed: the entire applet has only one app instance, which is shared across all pages, and more event callbacks refer to the registration document for the app. The event callback reference for the page

configuration

Global configuration: app.json

Common Configuration Items

  • Pages Indicates the page path list
  • Window Specifies the global default window representation
  • At the bottom of the tabBar
  • TAB column performance
  • networkTimeout
  • Network timeout
  • Debug Whether to enable the debug mode. By default, the debugging mode is disabled
{ "pages": ["pages/index/index", "pages/logs/index"], "window": { "navigationBarTitleText": "Demo" }, "tabBar": {" a list ": [{" pagePath" : "pages/index/index", "text", "home page"}, {" pagePath ":" pages/logs/logs ", "text" : "Log"}]}, "networkTimeout": {"request": 10000, "downloadFile": 10000}, "debug": true,}Copy the code

Page configuration: page.json

The configuration items in the page overwrite the same configuration items in the window of app.json.

Common Configuration Items

  • NavigationBarBackgroundColor navigation bar background color
  • NavigationBarTextStyle Navigation bar title color, black and white only
  • NavigationBarTitleText navigationBarTitleText content
  • BackgroundColor the backgroundColor of the window
  • BackgroundTextStyle Dropdown loading style, which supports only dark/Light
{ "navigationBarBackgroundColor": "#ffffff", "navigationBarTextStyle": "black", "navigationBarTitleText": BackgroundColor: "# eeEEee ", backgroundTextStyle: "light"}Copy the code

JSON Comments

JSON files are wrapped in curly braces {} to express data in key-value format. The JSON Key must be wrapped in double quotes. Annotations cannot be used in the JSON file, and attempts to add annotations will raise an error.

JSON values can be in only one of the following data formats. Any other format will trigger an error, such as undefined in JavaScript. Numbers, including floating point and integer strings, need to be enclosed in double quotes Bool values, true or false arrays, need to be enclosed in square brackets [] objects, need to be enclosed in curly braces {} Null

WXML template syntax

Data binding

<view>{{message}}</view>
Copy the code
Page({ data: { message: 'Hello MINA! '}})Copy the code

Component attributes

<view id="item-{{id}}"> </view>
Copy the code
Page({
  data: {
    id: 0}})Copy the code

The ternary operation

The ternary operation

<view hidden="{{flag ? true : false}}"> Hidden </view>
Copy the code

Arithmetic operation

<view> {{a + b}} + {{c}} + d </view>
Copy the code
Page({
  data: {
    a: 1.b: 2.c: 3}})Copy the code

String operation

<view>{{"hello" + name}}</view>
Copy the code
Page({
  data: {name: 'MINA'}})Copy the code

logic

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

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

<view hidden = "{{length > 5}}">
</view>
Copy the code

The list of rendering

<view wx:for="{{array}}" wx:key="index">
  {{index}}: {{item.message}}
</view>
Copy the code
Page({
  data: {
    array: [{
      message: 'foo'}, {message: 'bar'}]}})Copy the code
<view wx:for="{{array}}" wx:for-index="idx" wx:for-item="itemName">
  {{idx}}: {{itemName.message}}
</view>
Copy the code

block

<block wx:for="{{[1, 2, 3]}}">
  <view> {{index}}: </view>
  <view> {{item}} </view>
</block>
Copy the code

reference

WXML provides two file references: import and include.

<! -- item.wxml --><template name="item">
    <text>{{text}}</text>
  </template>
Copy the code
  <import src="item.wxml"/>
  <template is="item" data="{{text: 'forbar'}}"/>
Copy the code
<! -- index.wxml -->
<include src="header.wxml"/>
<view> body </view>
<include src="footer.wxml"/>

<! -- header.wxml -->
<view> header </view>

<! -- footer.wxml -->
<view> footer </view>
Copy the code

WXSS style

Dimensions in RPX

RPX = 1px under iphone6 (375)

Style import

@import "common.wxss";
.middle-p {
  padding:15px;
}
Copy the code

Style Other additions

<view style="color:{{color}};" />
<view class="normal_view" />
Copy the code

Introducing font ICONS

Support online font ICONS or font ICONS into base64 format after introduction

@font-face {
  font-family: "minifont";
  src: url("//at.alicdn.com/t/font_2593266_on928f0odc7.woff2?t=1622818124627")
      format("woff2"),
    url("//at.alicdn.com/t/font_2593266_on928f0odc7.woff?t=1622818124627")
      format("woff"),
    url("//at.alicdn.com/t/font_2593266_on928f0odc7.ttf?t=1622818124627")
      format("truetype");
  font-weight: 500;
  font-style: normal;
  font-display: swap;
}
Copy the code

Install Easy Less or Easy Sass using LESS /sass VScode to add configuration

 'less.comile': {
   'outEXt': '.wxss'
 }
Copy the code

Flex layout

align-items: baseline | stretch; / / the baseline aligned | stretch

The sample

      .container {
        display: flex;
        flex-direction: row;
        align-items: stretch;
        width: 375px;
        height: 375px;
        background: rgb(68.67.67);
      }

      [class*="item-"] {
        width: 100px;
      }

      .item-red {
        background: red;
      }

      .item-green {
        background: green;
      }

      .item-blue {
        background: blue;
      }
Copy the code
    <div class="container">
      <div class="item-red">
        1
      </div>
      <div class="item-green">
        2
      </div>
      <div class="item-blue">
        3
      </div>
    </div>
Copy the code

Instead of giving the child height, give the parent align-items: stretch; , the child element is stretched to the parent element’s height.

      .container {
        display: flex;
        flex-direction: row;
        align-items: baseline;
        width: 375px;
        height: 375px;
        background: rgb(68.67.67);
      }

      [class*="item-"] {
        width: 100px;
      }

      .item-red {
        background: red;
        font-size: 20px;
      }

      .item-green {
        background: green;
        font-size: 25px;
      }

      .item-blue {
        background: blue;
        font-size: 30px;
      }
Copy the code

align-items: baseline; Baseline versus.

There is no need to explain too much about baseline, which is related to CSS line height and font size. If you are interested or not, you can search CSS line-height online.

flex-wrap: wrap; A newline

      .container {
        display: flex;
        flex-direction: row;
        flex-wrap: wrap;
        justify-content: center;
        align-items: center;
        width: 375px;
        height: 300px;
        background: rgb(68.67.67);
      }

      [class*="item-"] {
        width: 150px;
        height: 150px;
      }

      .item-red {
        background: red;
      }

      .item-green {
        background: green;
      }

      .item-blue {
        background: blue;
      }
Copy the code

When the parent element has been set context-content: center; align-items: center; Flex-wrap: wrap; If the height of the parent element is greater than the number of rows × the height of the child elements, then there will be a gap between the rows. Setting the height of the parent element to the number of rows × the height of the child elements is a crude solution.

component

Container view

Common attribute: hover-class The style class pressed.

 <view hover-class="van-action-sheet"></view>
Copy the code

Text text

Common attributes:

  • Selectable text optional (deprecated)
  • User-select Specifies whether the text is optional
  • Decode Whether to decode

The picture image

Default: 320px wide and 240px high

Common attributes:

  • Mode Common values for image clipping include aspectFit and widthFix

Slider view container swiper

<view class="page-section page-section-spacing swiper"> <swiper indicator-dots="{{indicatorDots}}" autoplay="{{autoplay}}" interval="{{interval}}" duration="{{duration}}"> <block wx:for="{{background}}" wx:key="*this"> // *this indicates a loop item. [1, 2, 3], [' 1 ', '2', '3'] < swiper - item > < the view class = "swiper - the item {{item}}" > < / view > < / swiper - item > < block > < / swiper > < / view >Copy the code

Page link navigator

<view class="btn-area"> <navigator url="/page/navigate/navigate? Title =navigate" hover-class="navigator-hover"> to return to a new page </navigator> <navigator URL =".. /.. /redirect/redirect/redirect? Title =redirect" open-type="redirect" hover-class="other-navigator-hover"> open </navigator> <navigator Url ="/page/index/index" open-type="switchTab" hover-class="other-navigator-hover"> Toggle Tab</navigator> <navigator Target ="miniProgram" open-type="navigate" app-id="" "path="" extra-data="" version="release"> Open the bound applet </navigator> </view>Copy the code

Video video

<video id="myVideo" src="http://wxsnsdy.tc.qq.com/105/20210/snsdyvideodownload?filekey=30280201010421301f0201690402534804102ca905ce620b1241b 726bc41dcff44e00204012882540400&bizid=1023&hy=SH&fileparam=302c020101042530230204136ffd93020457e3c4ff02024ef202031e8d7f0 2030f42400204045a320a0201000400" danmu-list="{{danmuList}}" enable-danmu danmu-btn controls> </video>Copy the code

The scrollable view area is scrollable view

Input fields input

The search box

<input confirm-type='search' bindconfirm='shop_search_function'/>
Copy the code
Customize component components
<view class="my_header">
  {{cData}}
  <view>
    <slot name="before"></slot>
    <slot name="after"></slot>
  </view>
</view>
Copy the code
Component({ options: { multipleSlots: True // Enable multi-slot support in component definition options}, // Code sharing between components // The behaviors that override references are superimpose: [myBehavior], properties: {// The innerText property is defined here. The value of the innerText property can be specified when used by the component. // externalClasses: ['f-class'] // Data: {// {// data listener // Do not modify the listening value within the listening value causes the recursion 'numberA, numberB': Function (numberA, numberB) {// When numberA or numberB is set, execute the function} 'somedata. subfield': Function (subfield) {/ / using setData installed this. SomeData. Some. The subfield triggered when / / (in addition to this, }, 'somedata. list[12]': Function (arr12) {// Use setData to set this.somedata. arr[12]. }, 'somedata.field.**': Function (field) {// Use setData to set this.somedata.some. field itself or any of its child data fields. Using setData to set this.data.some will also trigger)},} methods: {/ / this is a custom method customMethod (event) {/ / modify the parent component by value let the innerText = this. The properties, the innerText let text = This.properties. Text this.setData({innerText: 'Changed value ', text: 'Changed value'}) this.triggerEvent('posttap',{pid:1}) // will only trigger posttap // look at communication between components and events}}})Copy the code
// my-behavior.js
module.exports = Behavior({
  behaviors: [],
  properties: {
    myBehaviorProperty: {
      type: String
    }
  },
  data: {
    myBehaviorData: {}
  },
  attached: function(){},
  methods: {
    myBehaviorMethod: function(){}
  }
})
Copy the code

The component registration

{
  "usingComponents": {"PageHeader": "page/to/"}}Copy the code

Using the component

<PageHeader innerText=" showing "F-class ="movie-list" Bind :customMethod="posttap"> <view slot="before"> Here is insert into component slot Name ="before" </view> <! <view slot="after"> </view> </PageHeader>Copy the code
  posttap(event){
    // Gets the custom event pass parameter
    console.log(event.detail.pid)
  }
Copy the code

Custom tabbar

Copy the widget’s official custom tabBar example custom-tab-bar to the root of the project (the same level as Pages)

The tabBar TAB in app.json specifies the Custom field, and other tabbar-related configurations are completed. UsingComponents must be declared in the JSON TAB page, and can be enabled globally in app.json.

Add the following code to the tabbar page onShow() page

  onShow() {
    if (typeof this.getTabBar === "function" && this.getTabBar()) {
      this.getTabBar().setData({
        selected: 2.// Select tabbar 0 as the first TAB}); }},Copy the code

Custom navigation

I found a good Github component through Bilibili’s video. I put the address in the relevant materials.

Generate qr code

Appellate P-qrcode Use methods

  <canvas style="width: 200px; height: 200px;" canvas-id="myQrcode"></canvas>
Copy the code
App.app.js import drawQrcode from '... /.. /utils/weapp.qrcode.min.js' data: { }, draw () { drawQrcode({ width: 160, height: 160, x: 20, y: 20, canvasId: 'myQrcode', // ctx: wx.createCanvasContext('myQrcode'), typeNumber: 10, text: '123', callback(e) { console.log('e: ', e) } }) } onLoad: function(options) { this.draw() },Copy the code

Wxapp-qrcode Usage method

<canvas style="width: 686rpx; height: 686rpx; background:#f1f1f1;" canvas-id="mycanvas"/>Copy the code
import QR from '.. /.. /utils/qrcode.js' data: { imagePath: '' }, onReady: function() { this.createQrCode('wxapp-qrcode', 'mycanvas', 300, 300) }, createQrCode: Function (content, canvasId, cavW, cavH) {// Call the draw method in the plugin to draw the two-dimensional code image. Draw (Content, canvasId, cavW, cavH, this, this.canvastotempImage); CanvasToTempImage: function (canvasId) {let that = this; Wx.canvastotempfilepath ({canvasId, // canvasId = canvas-id success: function (res) { let tempFilePath = res.tempFilePath; console.log(tempFilePath); SetData ({this.imagePath = tempFilePath imagePath:tempFilePath,}); }, fail: function (res) { console.log(res); }}); }Copy the code
Component library
  • Weui – WXSS: Official design team of wechat
  • iview-weapp
  • Vant – weapp: praise
  • MinUI
  • wux-weapp
  • ColorUI
  • Linui

Component library usage

For example: Linui

  • Init in applets and directories
  • Find the tool and click Build NPM
  • Certified components
// Global local registration is consistent
{
  "usingComponents": {"l-avatar":"/miniprogram_npm/lin-ui/avatar/index"}}Copy the code

JS logic interaction

The event

Unlike bind, catch prevents bubbling

<view id="outer" bind:tap="handleTap1"> outer view <view id="middle" catchtap="handleTap2"> middle view <view id="inner"  bind:tap="handleTap3"> inner view </view> </view> </view>Copy the code
setData
// For an object or array field, it is usually better to modify a subfield directly below it than to modify the entire object or array

this.setData({
  'array[0].text':'changed data'.'object.text': 'changed data'  
})
Copy the code
The module
function sayHello(name) { console.log(`Hello ${name} ! `) } function sayGoodbye(name) { console.log(`Goodbye ${name} ! SayHello = sayHello exports.sayGoodbye = sayGoodbye var common = require('common.js') Page({)} module.exports.sayHello = sayHello exports.sayGoodbye = sayGoodbye var common = require('common.js') Page({ helloMINA: function() { common.sayHello('MINA') }, goodbyeMINA: function() { common.sayGoodbye('MINA') } })Copy the code

Custom attributes

Start with data-.

<view 
  data-alpha-beta="1" 
  data-alphaBeta="2" 
  bindtap="bindViewTap"> 
  DataSet Test 
</view>
Copy the code
Page ({bindViewTap: function (event) {event. The currentTarget. Dataset. AlphaBeta = = = 1 / / - turn hump Event. The currentTarget. Dataset. Alphabeta = = = 2 / / capital will be converted to lowercase}})Copy the code

Operating the dom

<canvas canvas-id="qrcode"></canvas>Copy the code
  onLoad:function(){},
  onReady:function(){
    const query = wx.createSelectorQuery()
    query.select('#the-id').boundingClientRect()
    query.selectViewport().scrollOffset()
    query.exec(function (res) {
      res[0].top       // #the-id specifies the upper boundary of the node
      res[0].bottom    // #the-id specifies the lower boundary of the node
      res[1].scrollTop // Displays the vertical scrolling position of the region
      console.log(res)
    })
    console.log(query);

    var context = wx.createCanvasContext('qrcode')
    context.setStrokeStyle("#00ff00")
    context.setLineWidth(5)
    context.rect(0.0.200.200)
    context.stroke()
    context.setStrokeStyle("#ff0000")
    context.setLineWidth(2)
    context.moveTo(160.100)
    context.arc(100.100.60.0.2 * Math.PI, true)
    context.moveTo(140.100)
    context.arc(100.100.40.0.Math.PI, false)
    context.moveTo(85.80)
    context.arc(80.80.5.0.2 * Math.PI, true)
    context.moveTo(125.80)
    context.arc(120.80.5.0.2 * Math.PI, true)
    context.stroke()
    context.draw()
  }
Copy the code

WXS

WXS I use it as a filter in VUE

Example usage:

  // /filter/filter.wxs
  var foo = "'hello world' from tools.wxs";
  var bar = function (d) {
    return d;
  }
  module.exports = {
    FOO: foo,
    bar: bar,
  };
  module.exports.msg = "some msg";
Copy the code
  <! -- page/index/index.wxml -->
  <wxs src=". /.. /filter.wxs" module="filter" />
  <view> {{tools.msg}} </view>
  <view> {{tools.bar(tools.FOO)}} </view>
Copy the code

Thousands filter

function Thousands(num) { //num = parseInt(num); var num = num + ""; var d = ""; if (num.slice(0, 1) == "-") { d = num.slice(0, 1); num = num.slice(1); } var len = num.length; var index = num.indexOf("."); if (index == -1) { num = num + ".00"; } else if (index + 2 == len) { num = num + "0"; } var index = num.indexOf("."); Var num2 = num. Slice (-3); num = num.slice(0, index); var result = ""; while (num.length > 3) { result = "," + num.slice(-3) + result; num = num.slice(0, num.length - 3); } if (num) { result = num + result; } return d + (result + num2); } // {{filter.Thousands(1000)}}Copy the code

Time filter

function formatTime(str) { var formatNumber = function (n) { n = n.toString(); return n[1] ? n : "0" + n; }; var date = getDate(str); var year = date.getFullYear(); var month = date.getMonth() + 1; var day = date.getDate(); var hour = date.getHours(); var minute = date.getMinutes(); var second = date.getSeconds(); return ( [year, month, day].map(formatNumber).join(".") + " " + [hour, minute, second].map(formatNumber).join(":") ); } {{filter.formatTime(' timestamp ')}}Copy the code

API

Commonly used API

routing

The page stack in the applets is up to ten layers.

  • Reduce unnecessary use of wX. navigateTo.
  • To trigger the destruction page onUnload lifecycle execution method, routes that do not have a page stack must be used. Wx. reLaunch, wx.redirectTo, wx.navigateBack.
  wx.redirectTo({
   url:'/pages/address/address'
  })
  // Triggered when the page is uninstalled. As wx.redirectTo or wx.navigateBack to other pages.
  onUnload:function(){
  let pages = getCurrentPages().length - 1;
    console.log('Pages to be destroyed:'+pages);
    wx.navigateBack({
      delta: pages  // Close the current page and go to the previous page. However, jumping to the Tabbar page is not allowed. parameter})}Copy the code
wx.navigateTo({
  url: ''
})
wx.redirectTo({
  url: ''
})
Copy the code

Show action menu wx.showactionSheet ({})

Open another small program

wx.navigateToMiniProgram({
  // Open the appid of the applet
  appId: ' '.// Query data can be retrieved from the app. onLaunch, app. onShow, and page. onLoad callbacks of the open Page path and parameter applets
  path: 'page/index/index? id=123'.// The data that needs to be passed to the target applet. The target applet can get this data in app. onLaunch, app.onshow.
  extraData: {
    foo: 'bar'
  },
  // Demo, development, official
  envVersion: 'develop'.success(res) {
    // Open successfully}})Copy the code

Return to the previous applet

Wx. NavigateBackMiniProgram ({extraData: {foo: 'bar'}, success (res) {/ / return success}})Copy the code

To get the user’s location, just:

wx.getLocation({
  type: "wgs84".success: res= > {
    var latitude = res.latitude; / / latitude
    var longitude = res.longitude; / / longitude}});Copy the code

To invoke wechat scan capability, only:

wx.scanCode({
  success: res= > {
    console.log(res); }});Copy the code

Dynamically sets the title of the current page

Wx.setnavigationbartitle ({title: 'current page'})Copy the code

Hide the tabbar

  wx.showTabBar()
  wx.hideTabBar()
Copy the code

Copy the text

wx.setClipboardData({
  data: 'data',
  success (res) {
    wx.getClipboardData({
      success (res) {
        console.log(res.data) // data
      }
    })
  }
})
Copy the code

function

The background music

Page({
  data: {
      _mgr: wx.getBackgroundAudioManager()
  },
  onLoad(options){
    this.data._mgr.onPlay(this.onMusicStart)
    this.data._mgr.onStop(this.onMusicStop)
    this.data._mgr.onPause(this.onMusicStop)
  }
  onMusicStart(event){
      mgr.src = music.url
      mgr.title = music.title
      mgr.coverImgUrl = music.coverImg
  } 
  onMusicStop(event){}})Copy the code
// app.json
{
    "requiredBackgroundModes": ["audio"."location"]}Copy the code

Forward to share

  Page({
    onShareAppMessage: function (res) {
      if (res.from === 'button') {
        // from the page forward button
        console.log(res.target)
      }
      return {
        title: 'Custom Forwarding title'.path: '/page/user? id=123'}}})Copy the code
<button open-type="share"> </button>Copy the code

Scan code into applets or get parameters

Small program development/development Settings/scan common link two-dimensional code to open the small program, wechat scan code directly open the small program, small program scan code, get parameters.

Scan ordinary TWO-DIMENSIONAL code to open small program

Gets the small program code

  • auth.getAccessToken
  • wxacode.getUnlimited
  • Wechat applets with parameter applets code
  • Wechat mini program scans the TWO-DIMENSIONAL code and small program code to enter and obtain carrying parameters

WeChat pay

Contrast the column JSAPI JSSDK Small program
Unified order Both need to get the Openid first and call the same API
Call up the data signature Five fields involved in signature (case sensitive) : appId, nonceStr, package, signType, timeStamp
Invokes the payment page protocol HTTP or HTTPS HTTP or HTTPS HTTPS
Pay the directory There are There are There is no
Authorization of the domain name
The callback function The success callback Complete, fail, success callback functions
wx.requestPayment({
  timeStamp: ' '.nonceStr: ' '.package: ' '.signType: 'MD5'.paySign: ' ',
  success (res) { },
  fail (res) { }
})
Copy the code

Real-time audio and video screenshot

  • Screenshots: LivePlayerContext. The snapshot (string quality)
  • Save image: wx. SaveImageToPhotosAlbum (Object Object)

skills

Do not bind data. It is recommended to start with _, for example, _postsCollected

Values are passed between pages

  1. OnShow requests the interface directly
  2. GlobalData stores data onShow to refresh data
  3. Get the page instance and call the page method
  Page({
     onCartAdd(num) {
        // Get the page stack
        let pages = getCurrentPages()
        // Get an instance of the current page
        let currentPage = pages[pages.length - 1]
        // Get the route of the current page
        const url = currentPage.route;
        // Use the method of the current pagecurrentPage.onCartAdd(num); }})Copy the code
  1. EventBus (or PubSub)
  2. GloabelData watcher way
  3. The methods of the communication page are called directly by the hack method

Values are passed between components

Getting component instances

  // In the parent component
  onReady:function(){
    // Get an example of a child component
    this.child = this.selectComponent('.the-id');
    // methods in child components
    this.child.showToast()
  }

  <my-component id="the-id" />
Copy the code

The use of async/await

Promise is supported in the applet, but there are still problems with actual development. Such as:

  this.getArticle.then(res= >{
    console.log(res);
    // We want to wait for this asynchronous execution to complete before executing another asynchronous execution
  }).then(() = >{
    // We need to write this chain structure
    this.getArticle.then(res= >{
      console.log(res= >{
        console.log(res);
      })
    })
  })
  .catch(error= >{
    console.log(error);
  })
Copy the code

Nesting is unavoidable in this case, but maybe I didn’t understand promise very well. At this point I think of async/await but async/await is ES7 syntax.

  • Do not check ES6 to ES5, do not check enhanced compilation; This pattern is pure ES7 async/await and requires a higher version of the base library.
  • Check ES6 to ES5, check enhanced compilation; This is usually because a third party ES5 plug-in is called, with enhanced compilation to support async/await.
  • Select ES6 to ES5, do not select enhanced compilation; Manual introduction of Runtime.js support async/await.

We need to import runtime.js from [regenerator-Runtime]. Before you do that, you need to find a folder and save it locally. For example, lib \ runtime \ runtime js

Regenerator-runtime Independent runtime for compiled generators and async functions.

  / / my page
  import regeneratorRuntime from '.. /.. /lib/runtime/runtime';
  async getGoodsList(){
    const res=await request({url:"/goods/search".data:this.QueryParams});
    // Get the total number of entries
    const total=res.total;
    // Count the total pages
    this.totalPages=Math.ceil(total/this.QueryParams.pagesize);
    // console.log(this.totalPages);
    this.setData({
      // Concatenates arrays
      goodsList:[...this.data.goodsList,...res.goods]
    })

    No error is reported if the window is closed without calling the drop-down refresh
    wx.stopPullDownRefresh();
  },
Copy the code

API Promise style

  • Small program extension capability/tool class library /API Promise
  • WxService – Promise API
  • wx-promise-pro
  • Self Promise encapsulation
  • Hijack WX
  • Copying model
  • The proxy pattern
  /** * Promise form getSetting */
  export const getSetting=() = >{
    return new Promise((resolve,reject) = >{
      wx.getSetting({
        success: (result) = > {
          resolve(result);
        },
        fail: (err) = >{ reject(err); }}); })}/** * promise form chooseAddress */
  export const chooseAddress=() = >{
    return new Promise((resolve,reject) = >{
      wx.chooseAddress({
        success: (result) = > {
          resolve(result);
        },
        fail: (err) = >{ reject(err); }}); })}/** * Promise form openSetting */
  export const openSetting=() = >{
    return new Promise((resolve,reject) = >{
      wx.openSetting({
        success: (result) = > {
          resolve(result);
        },
        fail: (err) = >{ reject(err); }}); })}/** * promise form showModal *@param {object} * / param0 parameters
  export const showModal=({content}) = >{
    return new Promise((resolve,reject) = >{
      wx.showModal({
        title: 'tip'.content: content,
        success :(res) = >{
          resolve(res);
        },
        fail:(err) = >{ reject(err); }})})}/** * promise form showToast *@param {object} * / param0 parameters
  export const showToast=({title}) = >{
    return new Promise((resolve,reject) = >{
      wx.showToast({
        title: title,
        icon: 'none'.success :(res) = >{
          resolve(res);
        },
        fail:(err) = >{ reject(err); }})})}/** * Promise form login */
  export const login=() = >{
    return new Promise((resolve,reject) = >{
      wx.login({
        timeout:10000.success: (result) = > {
          resolve(result);
        },
        fail: (err) = >{ reject(err); }}); })}/** * a small program in the form of promise for wechat payment *@param {object} Pay Specifies the required parameters */
  export const requestPayment=(pay) = >{
    return new Promise((resolve,reject) = >{ wx.requestPayment({ ... pay,success: (result) = > {
        resolve(result)
      },
      fail: (err) = >{ reject(err); }}); })}/ / use
  import { getSetting, chooseAddress, openSetting, showModal, showToast, requestPayment } from ".. /.. /utils/asyncWx.js";
  requestPayment(pay);
  // The code source is black horse
Copy the code

Request to packaging

  • A minimalist promise encapsulates the interface
  // The number of times asynchronous code was sent simultaneously
  let ajaxTimes=0;
  export const request=(params) = >{
    // Check whether /my/ is a private path with a header token
    letheader={... params.header};if(params.url.includes("/my/")) {// Splice header with token
      header["Authorization"]=wx.getStorageSync("token");
    }
    ajaxTimes++;
    // Display the loading effect
    wx.showLoading({
      title: "Loading".mask: true
    });
    // Define the public URL
    const baseUrl="https://api.zbztb.cn/api/public/v1";
    return new Promise((resolve,reject) = >{ wx.request({ ... params,header:header,
      url:baseUrl+params.url,
      success:(result) = >{
        resolve(result.data.message);
      },
      fail:(err) = >{
        reject(err);
      },
      complete:() = >{
        ajaxTimes--;
        if(ajaxTimes===0) {// Close the waiting iconwx.hideLoading(); }}}); })}/ / use
  import { request } from ".. /.. /request/index.js";
  request({url:"/goods/search".data:this.QueryParams}).then(res= >{
    console.log(res);
  })
  // The code source is black horse
Copy the code
  • Request to packaging
  • WxRequest – Send a request
  • Secondary encapsulation of wechat applets wx.request

Chinese garbled

In the process of scanning code and page value transmission, there is the situation of Chinese transmission gibberish, which requires encodeURIComponent() encoding or decodeURIComponent() decoding.

Skeleton screen

Return key

  // Lifecycle function -- listens for page unloads
  onUnloadfunction ({
    wx.redirectTo({
      url"/pages/index/index"}); },Copy the code

The drop-down refresh

When is it best to use scroll view? I currently feel that when customizing the navigation bar, customizing the navigation will cause the entire page to be pulled down. But there are a few problems with using scroll view:

  • Pull up refresh loading animation, with native entire page will move, need to set, pay attention to compatibility.
  • The drop down load more Bindscrolltolower events trigger the need to get the height and then dynamically set the height.

Canvas painting Painter

The chart wx – charts

new Date()

The results are inconsistent between Android and Ios. (Such problems are encountered on wechat mini programs and webApp.)

An alternative to setData

wx-updata

Get multiple picture information at once

  const promixify = (api) = > {
    return (options, ... params) = > {
      return new Promise((resolve, reject) = > {
        api(Object.assign({}, options, { success: resolve, fail: reject }), ... params) }) } }const getImageInfo = promixify(wx.getImageInfo)
  const images = ['img1.jpg'.'img2.jpg'.'img3.jpg']
  Promise.all(
    images.map(img= > getImageInfo({ src: img }))
  ).then((imageInfos) = > {
    console.log(imageInfos)
  })
Copy the code

Small program log monitoring toolFundebug

The background image

Applet cannot use local image as background image

Solutions include:

  • Convert the image to base64 format to import
  • Put the image on CND or server to import
  • Use the image tag as the background layer

Development of cloud

I don’t have much contact with cloud development, and I will share it after finishing my follow-up study. At present, the previous blog is a bit messy, so I will finish it here first. Original blog Address wechat applets from getting started to practical development – Fallen-down

The relevant data


  • [Video] Introduction to wechat small program Development √

  • [Video]2 hours easy to realize face recognition small procedures √

  • [Video]1-1. Wechat Small program cloud development — Custom tabBar middle bulge effect √

  • [Video]28 lessons quick play wechat mini program √

  • [Video] Micro channel small program entry and actual combat √

  • [Video] wechat mini program tutorial √

  • [Video] Zero basis play wechat small program

  • [Video] Pure commercial application – micro channel small program development combat

  • [Video] Easy to start wechat applets and cloud development

  • Tencent Cloud University – small program learning path course

  • Flex layout tutorial: Syntax √

  • Global configuration √

  • Page Configuration √

  • Small program custom tabBar√

  • Weapp – qrcode)

  • SelectorQuery wx. CreateSelectorQuery ())

  • Wechat applets operate the DOM element node wx.createsElectorQuery ()√

  • Wechat applet dynamic generation of two-dimensional code implementation code √

  • Wxapp – qrcode)

  • Wechat applet uses filter filter in several ways √

  • Regenerator)

  • The asynchronous request using async-await method in wechat applet becomes synchronous request √

  • Wechat mini program – achieve sharing (with parameters) √

  • Let wechat small program page communication between not become difficult √

  • NavigateTo invalid after setting the guide page √

  • Wechat small program setData complex array update, delete, add, splice √

  • Wechat applet uses keyboard search function √

  • Wechat applet regular check √

  • Applet changed to async/await mode √

  • DecodeURIComponent () URL decoder √

  • Wechat applet wx.request Secondary encapsulation √

  • Applets log monitoring tool √

  • Tencent online education mini program development practice road √

  • [wechat mini program] API Promise √

  • Wechat applet use function anti – shake and function throttling √

  • Applets destroy page method √

  • The scrollView bindscrolltolower event does not trigger √

  • Small program scroll view custom scroll refresh √

  • Painter)

  • Wx – charts)

  • Github 5 practical micro app development tools √

  • Wechat mini program in the date format in Android and iOS real machine compatibility problem pit √

  • GetImageInfo obtains information about multiple images at one time. Square root

  • Wechat mini program to upload photos after rotation problem solved √

  • Wechat mini program three ways to authorize login √

  • ScrollView and other components are highly adaptive √

  • Use ECharts√ in wechat applet

  • Echarts – for – weixin)

  • Small program promise tool use √

  • Strongly recommended several micro channel small program development tips, simple and practical √

  • The parent component of wechat applets calls the child component method √

  • Wechat small program, format thousandths and retain two decimal √

  • Wechat small program subscription message step pit initial experience √

  • Template message √

  • Optimization practice of promotion of small program advertising arrival rate √

  • Wechat small program code maximum limit of 2M solutions √

  • 2 hours to easily realize face recognition small procedures √

  • How to use font icon √ in wechat applet

  • Page routing of wechat applets (9)√

  • Note √ External style class references for VLANT-retry P components

  • U-miniprogram statistical analysis of buried point √

  • Wechat mini program search content display keyword highlight √

  • Small program to achieve copy and paste function √

  • Small program communication, data refresh page, event bus, the event bus iny of ultimate solution – bus | WeChat open community (qq.com))

  • Mitt: Implementation of small publish/subscribe model, component event management, page pass.

  • Add buried points to CodeZha’s blog -CSDN Blog buried points to wechat applet √

  • Add the margin-top property to the first box inside the scroll view and the scroll bar will appear

  • The customized component in IOS Scrollview is fixed. Procedure

  • Small program poster generation tool, visual editing directly generated code use, your poster you own

  • Wechat small program drag to generate posters

  • Wechat H5 webpage jump App, jump applet

  • Let’s do small program live!

  • Small program poster generation tool, visual editing directly generated code use, your poster you own

  • Wechat mini program to save pictures

  • Small procedures how to generate posters to share circle of friends

  • Wechat applet Canvas generates and saves pictures

  • Wechat applet canvas rounded rectangle drawing

  • Small program using canvas to achieve wave dynamic map, native canvas part of the limitations

  • Small program to dynamically generate canvas poster

  • Micro channel applets generated photo sharing

  • Wechat small program Canvas hiding does not affect Canvas drawing processing method

  • Wechat mini program to generate a page picture

  • Openid acquisition sequence and solve the openID asynchrony problem

  • How to use AR capabilities of applets

  • Wechat mini program popup component

  • Encapsulation of wechat applets

  • Mini program takes personal ID card through camera

  • Wechat applet custom head navigation bar and navigation bar background picture navigationStyle

  • Customizing navigation- Bar (adaptive for Android and Apple)

  • Small program authorization process


Open source

  • Navigation -bar√

  • Awesome – making – wechat – weapp)