Make writing a habit together! This is the fifth day of my participation in the “Gold Digging Day New Plan · April More text Challenge”. Click here for more details.

Introduces common things used in native applets development.

A small program structure

  • App.js: the logic of small programs. Generally, small projects in app.js do not have much code, only some such as detecting version updates and so on.

  • Json applets common configuration

    • Pages: page path list The path of pages is the file path of the page

        "pages": [
          "pages/index/index"."pages/my/my"."pages/logs/logs"].Copy the code
    • TabBar: Representation of the bottom TAB bar

      • Color: Default text color on TAB. Only hexadecimal color is supported
      • SelectedColor: the selectedColor of the text on the TAB. Only hexadecimal color is supported
      • BackgroundColor: the backgroundColor of a TAB, which can only be a hexadecimal color
      • BorderStyle: Color of the border on the tabbar, supported onlyblack / white
      • List: indicates the TAB list. For details, seelistProperty description: A minimum of two to a maximum of five tabs
        • PagePath: the pagePath, which must be defined in pages first
        • Text: indicates the text of the TAB button
        • IconPath: image path. The icon size is limited to 40KB and the recommended size is 81px by 81px. Network images are not supported. When Position is top, icon is not displayed.
        • SelectedIconPath: the selected image path. The icon size is limited to 40KB and the recommended size is 81px by 81px. Network images are not supported. When Position is top, icon is not displayed.
      • Position: Position of the tabBar. This parameter is supported onlybottom / top
      • TabBar: custom tabBar
      "tabBar": {
          "color": "# 999"."selectedColor": "#6576ff"."borderStyle": "black"."backgroundColor": "#fff"."list": [{"pagePath": "pages/index/index"."text": "Home page"."iconPath": "static/[email protected]"."selectedIconPath": "static/[email protected]"
            },
            {
              "pagePath": "pages/my/my"."text": "I"."iconPath": "static/[email protected]"."selectedIconPath": "static/[email protected]"}},Copy the code
  • Common configuration of style for app.wxSS applets

  • Pages directory: pages with applets

  • Json: configuration file of the page

    • NavigationBarBackgroundColor: navigation bar background color, such as# 000000
    • NavigationBarTextStyle: navigation bar title color, supported onlyblack / white
    • NavigationBarTitleText: navigationBarTitleText content
    • NavigationStyle: navigation bar style, support only the following values: ‘defaultDefault style \Custom ‘custom navigation bar, only keep the capsule button in the upper right corner. See note 2.
    • BackgroundColor: backgroundColor of a window
    • BackgroundTextStyle: A drop-down loading style, which is supported onlydark / light
    • BackgroundColorTop: Background color of the top window, supported only by iOS
    • BackgroundColorBottom: Background color of the bottom window, supported only by iOS
    • EnablePullDownRefresh: Whether to enable the global drop-down refresh function
    • OnReachBottomDistance: distance from the bottom of the page when the bottom-pulling event on the page is triggered, in unit of PX
    • PageOrientation: Screen rotation Settings, supportedauto / portrait / landscape
    • RestartStrategy: Restart policy configuration \
    • InitialRenderingCache: pageInitial render cacheConfiguration, supportstatic / dynamic
    • VisualEffectInBackground: cut the system background, to hide the page content, protect user privacy. supporthidden / none
    • HandleWebviewPreload: controlThe time to preload the next page. supportstatic / manual / auto
  • Static most static files refer to images, but the size of the image should not exceed 200KB

Click events

Common Events

This is usually bindtap, which prevents events from bubbling and binds the mut-bind event list with catch events

  • Touchstart: Finger touch begins
  • Touchmove: Moves after a finger is touched
  • ‘touchCancel’ : Interrupted finger touch, such as incoming phone alert, popover
  • Touchend: The end of a finger touch
  • Tap: Move away immediately after finger touch
  • Longpress: The tap event will not be triggered if the event callback function is specified and the event is triggered
  • Longtap: After finger touch, leave after more than 350ms (longpress event is recommended instead)
  • Transitionend: Triggered after WXSS Transition or wx.createAnimation ends
  • Animationstart: Triggered when a WXSS animation starts
  • Animationiteration: Raised when an iteration of a WXSS animation ends
  • Animationend: Triggered when a WXSS animation completes
  • Touchforcechange: On iPhone devices that support 3D Touch, retiming is triggered

Click the event to get the parameters

<button data-index="1" data-name='2' bindtap="handleClick"> This is a click event </button>Copy the code

You can see that this is a click event, data-xxx, to get the data of the page

Js file

 handleClick (even: any) {
    const { index, name } = even.currentTarget.dataset
    console.log(index, name)
 }
Copy the code

Life cycle

There’s one missingonLaunchThis life function is written in app.js

And then let’s look at the function that the applet just went into firing

Then switch to the life function triggered after the page

4. Common page tags

WXML:WXML (WeiXin Markup Language) is a set of tag Language designed by the framework, which can be combined with the basic components and event system to build the structure of the page.

Data binding

<! --wxml--><view> {{message}} </view>
Copy the code
// page.js
Page({
  data: {
    message: 'Hello MINA! '}})Copy the code

wx:for

<view wx:for="{{array}}"> {{item}} </view>


// page.js
Page({
  data: {
    array: [1.2.3.4.5]}})Copy the code

Conditions apply colours to a drawing

<! --wxml--><view wx:if="{{view == 'WEBVIEW'}}"> WEBVIEW </view>
<view wx:elif="{{view == 'APP'}}"> APP </view>
<view wx:else="{{view == 'MINA'}}"> MINA </view>


// page.js
Page({
  data: {
    view: 'MINA'}})Copy the code

And then there’s a template, which I’ll say later

input

The input of a applet is slightly different from the input of a vue. The input of a applet modifies data through an event binding

  • Bindinput: Triggered during keyboard input
  • Bindfocus: Triggered when the input box is focused
  • Bindblur: triggered when an input box loses focus,
  • Bindconfirm: Triggered when the finish button is hit
  • Bindkeyboardheightchange: This event is triggered when the keyboardheight changes

4. Jump between pages

Small application API address: developers.weixin.qq.com/miniprogram…

  • Wx. switchTab: Switches to the tabBar page and closes all non-Tabbar pages
  • Wx. reLaunch: Close all pages and open to a page within the app
  • Wx. redirectTo: Closes the current page and switches to a page in the application. However, jumping to the Tabbar page is not allowed.
  • Wx. navigateTo: Leave the current page and jump to a page in the app. But you cannot jump to the Tabbar page. Use wx.navigateBack to return to the original page. The page stack in the applets is up to ten layers.
  • Wx. navigateBack: Close the current page and return to the previous page or multi-level page. You can use getCurrentPages to get the current page stack and determine how many layers you need to return.
  • EventChannel: Event communication channel between pages
  • Wx. navigateToMiniProgram: Open another applet
  • Wx. NavigateBackMiniProgram: return to a small program. This call succeeds only if the current applet is opened by another applet. Note: wechat client is supported by iOS 6.5.9, Android 6.5.10 and above
  • Wx. exitMiniProgram: Exits the current applets. There must be click behavior for the call to succeed.

With the exception of wx.switchTab, all other pages can pass parameters

Communication events between pages

This must be wX. NavigateTo

For example, the my page sends data to the log page

my.js


    wx.navigateTo({
      url: '/pages/logs/logs'.events: {
        // Adds a listener to the specified event to get data from the opened page to the current page
        acceptDataFromOpenedPage: function(data) {
          console.log('acceptDataFromOpenedPage',data)
        },
        someEvent: function(data) {
          console.log('someEvent',data)
        }
      },
      success: res= > {
        res.eventChannel.emit('acceptDataFromOpenerPage', { data: 'Data for my page'})}})Copy the code

log.js

const eventChannel = this.getOpenerEventChannel()
eventChannel.emit('acceptDataFromOpenedPage', {data: 'test'});
eventChannel.emit('someEvent', {data: 'test'});
// Listen for acceptDataFromOpenerPage events to get data sent from the previous page to the current page via eventChannel
eventChannel.on('acceptDataFromOpenerPage'.function(data) {
   console.log(data)
})
Copy the code

Click the page jump, you can see

Sharing function

The user clicks in the upper right corner to forward onShareAppMessage

onShareAppMessage() {

    const promise = new Promise(resolve= > {
      setTimeout(() = > {
        resolve({
          title: 'Custom Forwarding title'})},2000)})return {
      title: 'Custom Forwarding title'.path: '/page/user? id=123',}}Copy the code

Return An object that is used to customize favorites

- title: page title or account name - path: -imageurl: w:h=1:1 - PROMISE: If this parameter exists, the result of resolve will be used. If resolve is not found within 3 seconds, the share will use the default parameter passed in aboveCopy the code

In addition to times, you can also use the button button to forward

<button open-type="share"</button>Copy the code

When using the Button event, onShareAppMessage returns an argument,

onShareAppMessage(even) {
    if(even.from === 'button') {
        // From button forward
    }

    return {
      title: 'Custom Forwarding title'.path: '/page/user? id=123',}}Copy the code

Even takes three arguments:

- from: indicates the source of the forwarding event. 'Button' : forwarding button within the page; -target: If 'from' is' button ', then 'target' is the 'button' that triggers this forwarding event, otherwise 'undefined' -webviewURL: Returns the url of the current web-view if the page contains a 'web-view' componentCopy the code

OnShareTimeline ()

The event handler returns an Object that can be used to customize the shared content. No custom page path is supported.

  • Title: Custom title, that is, the title displayed on the friends list page
  • Query: User-defined parameters carried in the page path, such as path? A = 1 & b = 2 “?” The back part
  • ImageUrl: Custom image path, can be a local file or network image. Support PNG and JPG, display picture aspect ratio is 1:1

You must also call wx.showShareMenu when using shared moments

wx.showShareMenu

Displays the forward button of the current page with the parameter Object

  • WithShareTicket: indicates whether to enable forwarding withShareTicket. [details]
  • Menus: This interface is a Beta version, and is only supported on the Android platform. List of forward button names to display, default [‘shareAppMessage’]. The value of a button name can be shareAppMessage or shareTimeline
  • Success: Callback function successfully invoked by the interface
  • Fail: Callback function that fails to be invoked by the interface
  • Complete: callback function at the end of an interface call (executed on success or failure)

Code:

 onLoad() {
    wx.showShareMenu({
        withShareTicket: true.menus: ['shareAppMessage'.'shareTimeline']})},onShareTimeline() {
    return {
      title: 'My page'.query: '/pages/my/my? id=1'.imageUrl:' '}},Copy the code

Collect onAddToFavorites


onAddToFavorites(res) {
    // WebView page returns webViewUrl
    console.log('webViewUrl: ', res.webViewUrl)
    return {
      title: 'Custom title'.imageUrl: 'http://demo.png'.query: 'name=xxx&age=xxx',}}Copy the code

6, modify data setData

General modification data

// wxml
<view>{{num}}</view>

// my.ts
Page({
  data: {
    num: 1,},onLoad() {
    this.setData({
      num: 2})}})Copy the code

Modify the data of an object

<view> data: {{userinfo.age}}</view> data: {userInfo: {
      name: 'Joe'.age: '100'}},this.setData({
   'userInfo.age': 1
})
Copy the code

Modify the array

list: [
   {id: 1.label: 'label1'},
   {id: 2.label: 'label2'},
   {id: 3.label: 'label3'},]this.setData({
   ['list[1].label'] :'I'm a changed label'
})
Copy the code

7. Access to user information

Access code wx. The login ()

wx.login({
  success (res) {
    if (res.code) {
      // Initiate a network request
      wx.request({
        url: 'https://example.com/onLogin'.data: {
          code: res.code
        }
      })
    } else {
      console.log('Login failed! ' + res.errMsg)
    }
  }
})

Copy the code

Get user information wx.getUserProfile

The API call must be a button button call

<button open-type="getUserInfo" bindgetuserinfo="getUserProfile"</button>Copy the code
getUserProfile() {
    // It is recommended to use wx.getUserProfile to obtain user information. Every time the developer obtains user information through this interface, the user needs to confirm. The developer should keep the profile name quickly entered by the user to avoid repeated popups
    wx.getUserProfile({
      desc: 'Show user information'.// Specify the purpose of obtaining the user's personal information, which will be displayed in the subsequent pop-up window
      success: (res) = > {
        console.log(res)
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true}}}})),Copy the code

To be continued!!