Small program reduction manual

Applet

1, Start

1. Developer Tools

Download address

2. Developer account

  • Company Registered Address : next step registration
  • After success, enter the page and click development = > development settings to see the AppID account

3. Create project

  • New folder
  • Open the development tool and input the file address without selecting cloud development
  • The project file is then initialized automatically

4. Preview project

  • Click the preview function of development tool to generate QR code
  • Mobile wechat scanning and viewing
  • Experience personnel management, which is configured in the member management on the registration address success page

2, Develop

1. Document introduction

  1. project.content.js: project configuration file

    • It is suggested to modify the options in the details
    • You can change AppID and projectname yourself
  2. sitemap.json: configure applet indexes, which are basically indexable

  3. App.js: register applet

  4. app.json: global configuration

    • pages: configure routing

    The route above is the home page

    • Window: configure window performance,

    Navigation bar color, font, font color, window background color, drop-down loading,

    Whether to pull down refresh, pull up to the top distance, and rotate the screen

    • entryPagePath: specify the first page not in the order of pages
    • Do it for him
  5. app.wxss: css file: wechat cannot use ID selector

  6. pages: there are page files

  7. Static: create your own folder to place static files

2. Development grammar

1. Create page

  • Create a file in pages, and then right-click to select add page. The file of the page will be automatically generated and displayed in app Register routing in JSON
  • view corresponds to div and text corresponds to span
  • Adaptation: 1px = 2rpx; The design drawing is 750
  • Note: add public style: page {height: 100%}

2. Current configuration page

Add app Get the index of the current page between the window attributes in JSON json

{
  "usingComponents": {},
  "navigationBarTitleText": "Hello" // Direct setting of current page
   // Local priority is greater than global priority 
}

js dynamic modification

wx.setNavigationBarTitle({ title: 'King Xu' })
// Document = > API = > interaction = > navigation bar
// There are other controls

3. Data binding

1. Create initialization data:

  • Under the page file, index Create data in the data of page object in JS

  • You can view the initialization data through the debugger's appData

  • View layer: < text > {{MSG}} < / text >

  • View layer:

    <view class="{{ classList.one }}, {{ active ? 'active' : '' }}"></view>

  • js: console.log(this.data.msg)

2. Modify data

  • js modify data: this setDate({ msg: 'success' }); synchronization

4. Event binding

  • Bubbling: < button bindtop = "handletap" > button < / button
  • No bubbles: < button catch = "handletap" > button < / button >
  • Bound event and data level
  • Tap is equivalent to click
  • touchstart: finger click: e.touches [0] clientY
  • touchmove: finger movement
  • touchend: finger lift

Pull up custom animation through distance judgment

style="transform: {{ coverTansform }}"

target: may be the current element or the parent element

currentTarget: it must be the current element

detail.value: the value returned by the form component

Event input parameters:

<view
  id="dataSet"
  data-alpha-beta="1"
  data-alphaBeta="2"
  bindtap="bindViewTap"
> DataSet Test </view>
Page({
  bindViewTap:function(event){
    event.currentTarget.id === dataSet
    event.currentTarget.dataset.alphaBeta === 1 // -Will change to hump writing
    event.currentTarget.dataset.alphabeta === 2 // Uppercase will be converted to lowercase
  	cosnt value = event.detail.value // value returned by the form component
  }
})

5. Conditional rendering

<view wx.if="{{ isUser }}">There are users</view>
<view wx.else >No user</view>

6. List rendering

  • Syntax: wx:for

  • The subscript variable name of the current item of the default array is index by default, and the variable name of the current item of the array is item by default

    <view wx:for="{{array}}">
      {{index}}: {{item.message}}
    </view>
    
    <!-- definition index, item alias -->
    <view
      wx:for="{{array}}"
      wx:for-index="idx"
      wx:for-item="itemName"
    >
      {{idx}}: {{itemName.message}}
    </view>
    
    <!-- key use -->
    <!-- arr=[{ name: 1 }, { name: 2 }] -->
    <view wx:for="{{ arr }}" wx:key="name">
    	{{ item.name }}
    </view>
    

7. Custom components

  • Create a new components folder, create nav files in the folder, and right-click to select new component

  • The four new files are the same as the page file, but the route will not be automatically added

  • Import Registration: at the bottom of the page usingComponents configuration in json file

    {
      "usingComponents": {
          "HeadBox": "/components/HeadBox/HeadBox"
      }
    }
    

8. Component value transfer

Value transfer between components: unable to transfer value

Parent to child:

<view>
	Parent component
    <Child title="Incoming value">Subcomponents</Child>
</view>
// There will be properties in the js of the sub component to receive and pass values
// Similar to the props of vue, value is equivalent to default
properties: {
    title: {
        type: String,
        value: 'Default value'
    }
}
// And the value of properties will be synchronized to data

Son to father

  • The parent creation event is passed to the child
  • The child calls the parent event to pass parameters
  • The parent event is called back through the event
  • You can also trigger then through promise's resolve to complete the reverse trigger

9. Parent-child event

  • Parent to child:

    <!-- Parent component -->
    <component-tag-name bindmyevent="onMyEvent" />
    
    // Parent component
    onMyEvent(e) { console.log(e.detail.name) }
    
    <!-- Subcomponents -->
    <button bindtap="onTap">Clicking this button will trigger“ myevent"event</button>
    
    // Subcomponents
    onTap() {
        this.triggerEvent('myevent', { name: 'xu' })
    }
    
  • Son to father:

    1. Define id for parent component and child component
    2. The parent component passes const son = this Selectcomponent ("#id") get sub components
    3. Then through son Go() calls the sub component go method
    4. The component list cannot be used when it is used. It needs to be implemented in other ways
  • Other ways

    • Use the third-party plug-in PubSub JS
    import Pubsub from 'pubsub-js'
    // subscribe
    const pubsub = Pubsub.subscribe("Subscription name", (msg, data) => {
        console.log(msg) // The pubsubID of the corresponding setting will be output here
        console.log(data) // The corresponding set parameters will be output here
    })
    // Unsubscribe
    Pubsub.unsubscribe(pubsub)
    // Cancel all subscriptions
    PubSub.clearAllSubscriptions()
    
    import Pubsub from 'pubsub-js'
    // release
    Pubsub.publish("Subscription name", data)
    // or
    PubSub.publishSync("Subscription name", data)
    

10. Template

  • Create a templates folder at the same level as pages

  • Create a test folder and create a new page

  • Write a template in wxml on the page with the help of template style

    <!-- Template -->
    <template name="msgItem">
      <view class="username">
        <text>username: {{ name }} </text>
      </view>
    </template>
    
    /* Template style */
    .msgItem {
        height: 40px;
        border: 1px solid red;
    }
    .username {
        line-height: 30px;
        font-size: 16px;
    }
    
  • Page usage template

    <import src="/templates/test/test.wxml" />
    <view>
    	<template is="msgItem" data="{{...item}}"/>
        <!-- item = { name: 'King Xu' } -->
    </view>
    
    @import "/templates/test/test.wxss"
    /* The style defined below will override the template style. Pay attention to the naming */
    

3. Routing and navigation components

  • Programming jump

    1. wx.navigateTo()

      wx.navigateTo({
          url: '/pages/index/index', // You must add a root path
          events: { callback: (data) => { console.log(data) } } 
          // The opened page gives feedback to the current page
          // Others include success callback, fail callback and complete jump callback
          success: (res) => {
          	 res.eventChannel.emit('reverse', { name: 'king' })
          }
      })
      // The jump record will be kept
      
      // Open page
      onLoad(options) {
          const eventChannel = this.getOpenerEventChannel()
          eventChannel.emit('callback', { name: 'Xu' });
          // Call the callback of the previous page
          eventChannel.on('reverse', (data) => { console.log(data) });
          // Callback from this page to the previous page
      }
      
    2. wx.navigateBack: equivalent to history go()

    3. wx.redirectTo(): no value transfer and no record saving

    4. wx.reLaunch(): close other, and then jump without value transfer

    5. wx.switchTab(): close other and jump to tabar page

  • Carry out value transfer

    The above method and can realize the transmission of parameters between the upper and lower components of the route

    Pass parameters and query through get (disadvantages: limited delivery)

  • Get passed value

    Get get parameters: onLoad(options) {}: options is the query passed by get

  • tabBar bottom navigation

  • Global tabBar

    It's directly on the app The tabBar attribute defined in JSON is the same level as window and pages

    It is described in the document = > framework = > global configuration = > tabbar

    icon cannot be used at the top, there will be a lower border, and 2 < = list length <= 5

    "tabBar": {
        "backgroundColor": "#f0f0f0",
        "color": '#333',
        "selectedColor": "#d43c33",
        "position": "botton/top",
        "custom": false,
        "list": [
            {
                "pagePath": "tabBar Navigation address",
                "text": "tab written words",
                "iconPath": "Unchecked  icon pictures linking",
                "selectedIconPath": "Select icon pictures linking"
            }
        ]
    }
    
  • Custom tabBar (local or global)

    1. Set custom to true, and then the configured list will become invalid
    2. Create a folder at the same level as the index tab component
    3. Then you can write a custom tabBar component in the component
    4. Be careful not to use the view tag, which may cause the page to overwrite the tabBar
    5. Replace view with cover view and cover image components

4. Life cycle

Page lifecycle

  • Initialization: onLoad() {}: execute only once
  • Page display: onShow() {}
  • Dom rendering complete: onReady() {}: execute only once
  • Page hiding: onHide() {}; When the page is hidden and displayed again, onShow() {} will be triggered
  • Page unload (page destroy): onUnload() {}

Component lifecycle: see custom component documentation

5. Data store

1. Data store management

  • On app JS file creates a globalData object to store the global data of the store

  • Use const appInstance = getApp() locally to get

    const appInstance = getApp();
    Page({
        onLoad() {
            console.log(appInstance.globalData.name)
            appInstance.globalData.name = "hello"
        }
    })
    

2. Data local storage

Similar to js local storage:

Synchronization: Wx Setstoragesync, multiple asynchronous methods Wx setStorage

Sync: Wx Getstoragesync, multiple asynchronous methods Wx getStorage

And remove, clear

6. Authorization

  1. First login trigger authorization

    <button bindgetuserinfo="handleGetInfo" open-type="getUserInfo">Obtain authorization</button>
    <!-- adopt bindgetuserinfo pick up information -->
    
  2. After authorization, you can use Wx getuserInfo(); Repeated acquisition of information

    wx.getUserInfo({
        success: () => {}, // Successful callback
        fail() {} // Failed callback, and the error will not be seen by the user
        complete() {} // Execute callback regardless of success or failure
    })
    // It is used in the onLoad cycle of the component after authorization
    

7. Components

1. Basic components

The built-in components of the applet include rotation chart, button and other native components

  • swapper: previous margin
  • swapper: next margin offset after adjustment

2. icon usage

  • Use case icon, create project, and use class name
  • Create iconfont folder in static = > index wxss
  • Copy the open code of the link provided by icon to the index Wxss file
  • On app Introduce @ import "/static/iconfont/index.wxss" into wxss
  • Usage: < text class = "iconfont icon type name" > < / text >

3. Scrollable view

Wechat built-in component scroll view

Scroll up and down, scroll left and right, pull-down refresh and other page scrolling functions

8. Request

  1. Interface request using Wx Request()

  2. The initialization request will be placed in onLoad or onReady

  3. The url address must be complete, and on the applet management page (that is, the page after successful registration), development = > development setting = > server domain name setting = > Add server domain name

  4. Add up to 20 domain names and no more than 10 concurrent domain names

  5. It must be https protocol. If not, you can set no verification in the development tool details first

    You don't need to add a domain name to the applet management page. You can debug locally

  6. File upload Wx UploadTask()

  7. File download Wx downloadFile()

  8. cookie carrying:

    • It is obtained during login and stored in local data or store
    • Login page adjustment other pages need to close other page adjustment, which is used to trigger onLoad of other pages
    • Other pages onLoad get the cookie, send the request, and put the cookie in the head attribute
    • wx. The head and url in the request document are at the same level
  9. encapsulation

    // utils/request.js
    
    

9. Intranet penetration

  • Solve the problem that the interface has no service during real machine debugging
  • Download uTools software for operation = > plug-in center = > intranet penetration
  • Then the configuration can realize the real machine debugging, but the debugging cannot be previewed

10. npm usage

  • Project file open cmd run npm init
  • Developer tool details = > project configuration = > using npm package
  • Developer tools = > build npm
  • Then you can use npm third-party plug-ins

11. Get login credentials

  • Use Wx login({ success(res) { console.log(res.code) } })
  • Then send the code to the backend
  • The back-end generates authentication token through code, and then has the function of login authentication

12. Applet subcontracting

  • Split packets larger than 2M and smaller than 16M

1. Conventional subcontracting

  • On app Configure subpackages in JSON; This is an array

    "subpackages": [
        {
          "root": "packageA",
          "pages": [
            "pages/cat",
            "pages/dog"
          ]
        }, {
          "root": "packageB",
          "name": "pack2",
          "pages": [
            "pages/apple",
            "pages/banana"
          ]
        }
    ]
    
  • Root: the root path name of the package

  • name: alias of package

  • pages: routing configuration of packets

  • Then create a package root path name folder at the same level as the main package pages for subcontracting, such as packageA

  • Then, the pages folder is also created in pageageA, which has the same structure as the main package

  • Subcontracting can use the main package resources. You can modify the path 🌙

  • The main packet jumps to the packet. The routing root path is the packet name

2. Independent subcontracting

  • Add "independent" to the configuration requiring independent subcontracting: true

    {
      "root": "packageB",
      "name": "pack2",
      "pages": [
        "pages/apple",
        "pages/banana"
      ],
      "independent": true
    }
    
  • Independent subcontracting cannot use the main packet resources, and the route jump is the same as that of conventional subcontracting

3. Subcontract preload

  • On app The preloadRule in JSON is configured

    "preloadRule": {
        "pages/index": {
          "network": "all",
          "packages": ["packageA"]
        },
        "sub1/index": {
          "packages": ["packageA", "packageB"]
        },
        "sub3/index": {
          "packages": ["packageB"]
        },
        "indep/index": {
          "packages": ["__APP__"]
        }
      }
    
  • "pages/index": open the routing path or package index path

  • Network: specify the network mode, wifi or others

  • packages: the root or name of the subcontract, where the main package is called__ APP__

3, Development experience

1. input get value

<view>
	<input type="text" id="text" bindinput="handleInput"/>
	<input type="password" id="password" bindinput="handleInput"/>
</view>
handleInput(e) {
    const type = e.currentTarget.id
    this.setData({
        [type]: e.detail.value
    })
}

2. Message prompt

  • Wechat native tip: Wx Showtoast ({Title: 'success'})
  • There are also tips for him: document = > API = > interface = > interaction

3. video multiple playback

  • Multiple playback of video is illogical

  • We need video to play next stop the current previous video

  • wx.createVideoContext: create a VideoContext object to manipulate video

  • Use case

    <view wx:for="{{array}}" wx:key="src">
        <video
           bindplay="handlePlay"
           src="{{item.src}}"
           id="{{item.data.id}}"
        />
    </view>
    
    handlePlay(e) {
        const vid = e.currentTaget.id;
        // Determine whether the same video & & determine whether the previous video control exists
        if (this.vid !== vid && this.VideoContent) {
            this.VideoContent.stop(); //Stop video playback
        }
        this.vid = vid
        this.VideoContext = wx.createVideoContext(vid);
    }
    

4. image instead of video

  • Use the poster attribute of video to add img links as native
  • Create an image and video peer
  • Judge whether the video is hidden through Wx: if = "{vid = = = item. Data. Vid}}" to realize optimization
  • At this time, the problem of multiple videos playing at the same time is also solved

5. Video area size

Use the property setting of object fit of video

6. Pull down refresh

  • scroll-view
  1. Refresh enabled of scroll view enables the pull-down refresh
  2. bindrefresherrefresh of scroll view monitors whether the drop-down is triggered
  3. The pull-down controllable state of scroll view: refresh triggered
  • The page also has a drop-down refresh
  1. The page has onPullDownRefresh life cycle function to monitor the pull-down trigger
  2. Drop down requires global or local setting enablePullDownRefresh to true
  3. Global on page JSON is set in the window
  4. The part is set in json
  5. Controllable state restoration is not required for page drop-down

7. Pull up loading

  • Pull up loading of scroll view: triggered by bindscrolltower property
  • Page pull-up loading: the onReachBottom life cycle function is triggered by monitoring

8. Share friends

  • button set the open type to share to trigger the function of sharing friends

  • Users click the share button at the top of the page

    The header sharing menu is only available when the onshareaappmessage lifecycle function is created

    After clicking the menu, the onShareAppMessage is triggered

    Use the form to determine whether the button triggers sharing or the header menu triggers sharing

  • Customize shared content

    onShareAppMessage can return an object to customize sharing

    title: title Path: share page path imageUrl: share pictures

9. Music playing

Music playback uses background audio function: document = > API = > media = > background audio

Effect, can continue to play after closing

Key: BackgroundAudioManager

Audio key: add playback monitoring in onLoad() {}, pause monitoring and stop monitoring

Playing, pausing, stopping, and natural stopping of music playing are all methods of BackgroundAudioManager

In addition, enter the update listening event to get the playback progress

Playback progress / total duration * progress bar width and length = current progress bar width and length

Keywords: Front-end Mini Program

Added by melrse on Tue, 08 Feb 2022 15:35:01 +0200