Getting Started with Mini Programs for WeChat Program Development

1. Mini Program Introduction

WeChat official document

Mini Program Life Cycle

// app.js
App({   onLaunch() {     // Show local storage capability     const logs = wx.getStorageSync('logs') || []     logs.unshift(Date.now())     wx.setStorageSync('logs' , logs)     // login     wx.login({       success: res => {         // send res.code to background to exchange for openId, sessionKey, unionId       }     })   },   onShow (options) {     // Do something when show.     console. log("show")   },   onHide () {     // Do something when hide.     console.log("hide")   },   onError (msg) {     console.log(msg)   },





 




       














  globalData: {
    userInfo: null
  }
})

Scan the QR code after successful installation

Create a small program

Interface after successful creation

We need to create a login at this time

 

index.wxss

image{
  width: 400px;
  height: 400px;
  border-radius: 50%;
}

index.wxml

<view>
  <navigator url="/pages/login/login">
    <button>Login</button>
  </navigator>
</view>

login.js

Page({
    data: {
        msg:"nihao",
        user:{
            username:"hmf",
            password:""
        }
    },
    bindName(e){
        //arguments are the parameters of the function
        //console.log(arguments)
        this.setData({
            "this.username":e.detail.value
        })
    },
    bindPwd(e){
        //arguments are the parameters of the function
        //console.log(arguments)
        this.setData({
            "this.userPwd":e.detail.value
        })
    },
    aa(){
        wx.showToast({
            title:"xx",
            icon:"success"
        })
    },
    bb(){
       this.data.user.username=""
        this.data.user.password=""
    }
})

login.wxml

<view>
    <image src="/aa/xf2.jpg" mode="aspectFit"/>
</view>
<view>
    <form bind:submit="aa" bind:reset="bb">
        <label>名字</label>
        <input value="{
   
   {user.username}}" bind:input="bindName" value="" type="text" placeholder="Please enter user name" maxlength="10"/>
        <label>Password</label>
        <input value="{
   
   {user.password}}" bind:input="bindPwd" value="" type="text" placeholder="Please enter user password" password="true" maxlength="10"/>
        <label>Hobbies</label>
        <checkbox-group>
            <checkbox checked="{
   
   {true}}">Drink milk tea</checkbox>
            <checkbox>k歌</checkbox>
            <checkbox>吃</checkbox>
        </checkbox-group>
        <radio-group>
            <radio value="女" checked="true">女</radio>
            <radio value="Male">Male</radio>
        </radio-group>
        <view>
            <button form-type="submit">登录</button>
            <button>Register</button>
            <button form-type="reset">清空</button>
        </view>
    </form>
    <view>
        {
   
   {user.username}}
    </view>
</view>

login successful

empty

 

 at last

00. A small program page consists of four files, namely:
  xxx     
    xxx.js page logic
    xxx.json page configuration
    xxx.wxml page structure
    xxx.wxss page style


01. Small program framework is composed
   of small programs, register a small program through App(), and register a page through Page()
   1. Logic layer
     1. Register small program
     2. Register page
     3. Page life cycle
     4. Page Routing
     5. Modularization
     6. API
   2. View layer
     1.
     wxml 2. wxss
     3. wxs
       wxs is the scripting language of the WeChat applet itself, used for filtering and calculation. wxs can be defined through the file module tag, the file needs the .wxs suffix file
       wxs is specially used for wxml pages, if you need to use js scripts in the page, you can use it, but wxs cannot be referenced by other js files
       . Development should choose to use js or wxs according to the situation, but most of my development is done in js

  
## Example 1: Mini Program Life Cycle
02. Registering Mini Programs
   Each mini program needs to call the App method in app.js to register a mini program instance, bind life cycle callback functions,
   error monitoring and page non-existence monitoring functions, etc.
   1. Create an App instance, the applet lifecycle function
   // app.js
   App({      onLaunch (options) {//Monitor applet initialization When the applet initialization is completed, onLaunch will be triggered (globally only triggered once)        // Do something initial when launch.      },      onShow (options) {//Monitor applet display When the applet starts, or enters the foreground display from the background, it will trigger onShow // Do something when        show.      },      onHide () {//Monitor applet Hide When the applet enters the background from the foreground, it will trigger onHide        // Do something when hide.      },      onError (msg) {//Error monitoring function When the applet has a script error or the api call fails, onError will be triggered and brought Error message        console.log(msg)      },      globalData: 'I am global data'













   })

   Note 1: Comparison with SPA projects
        1. Equivalent to defining global Vue objects in main.js in SPA projects,
        2. onLaunch/onShow/onHide/onError are equivalent to hook functions
   Note 2: Other developers can add arbitrary functions or data into the Object parameter, which can be accessed with this
          

   2. There is only one App instance in the whole applet, which is shared by all pages. Developers can
     obtain a globally unique App instance through the getApp method, obtain data on the App or call functions registered by the developer on the App.
     // xxx.js
     const appInstance = getApp()
     console.log(appInstance.globalData) // I am global data

## Example 2: Data Binding/Life Cycle/Data Inheritance
03. Registration Page
   For each page in the applet, you need to register in the js file corresponding to the page, and specify the initial data, life cycle callback, and event of the page
   Simple pages such as handler functions can be constructed using the Page(Object object) constructor.
   
   Page (Object object) constructor function:
   register a page in the applet. Accepts an Object type parameter, which specifies the initial data of the page, life cycle callbacks, event handlers, etc.

   Page({      data: {//The initial data used for the first rendering of the page        text: "This is page data."      },      onLoad: function (options) {//Monitor page loading        console.log("page ---onLoad ---");      },      onReady: function () {//Monitor page rendering completed for the first time        console.log("page ---onReady---");      },      onShow: function () {//Monitor page display        console.log("page ---onShow---");      },      onHide: function () {//Monitor page hide        console.log("page ---onHide---");      },      onUnload: function () {//Monitor page unload        console.log("page ---onUnload---");      }    })


















   Among them, after the applet is opened, the onLoad will be executed
   sequentially, the onReady and onShow methods will execute the onHide and onShow methods respectively, and
   the onUnload method will be executed when the applet page is destroyed.

   Note 1: How to make multiple pages have the same data fields and methods? Use behaviors in the page (there is no such function in vue)
        // my-behavior.js
        module.exports = Behavior({           data: {             sharedText: 'This is a piece of data shared between pages.111'           },           methods: {             sharedMethod : function() {               return "This is a piece of data shared between pages.222";             }           }         })








        // page-a.js
        var myBehavior = require('./my-behavior.js')
        Page({           behaviors: [myBehavior],           onLoad: function() {             console.log(this.data.sharedText)//inheritance Attributes and method calls             console.log(this.sharedMethod())           }         })    Note 2: The Page constructor is suitable for simple pages. But for complex pages, use the Component constructor to construct the page.         The main difference between the omponent constructor is: the method needs to be placed in methods: { }         Component({           data: {             text: "This is page data."           },           methods: {             onLoad: function(options) {               // execute when the page is created             },






        










            onPullDownRefresh: function() {               // Execute when pull down to refresh             },             // Event response function             viewTap: function() {               // ...             }           }         })







   Note 1: The important thing is said three times "Don't create a page in vscode, WeChat developer tools will not compile, just add ctrl+s to the pages of app.json" The important thing is said three times "Don't create a page in
        vscode , WeChat developer tools will not compile, just add ctrl+s to the pages of app.json "
        Say important things three times" Do not create pages in vscode, WeChat developer tools will not compile, in app.json Add ctrl+s to pages”


04. For details on the page life cycle (understanding)    
   , see: images/01 page-lifecycle.png

### Important
05. Mini Program Configuration
   1. Global Configuration File (Important)
     The app.json file in the root directory of the Mini Program is used to configure the WeChat Mini Program globally, determine the path of the page file,
     window performance, and set the network timeout , Set multiple tabs, etc.
     -tabbar (minimum 2 columns)
      Demo example: home page, shopping cart, my
      Note 1: Why does the TabBar not appear at the bottom? The first item of the pages array must be a member of the list array of the tabBar
      Note 2: At least 2 buttons, up to 5 
     -pages
      demonstration example: applet title, page title text
     -window
   2.sitemap.json (understand)    
     applet The sitemap.json file in the root directory is used to configure whether the applet and its pages are allowed to be indexed by WeChat

## Example 3: Page routing: Component jump (absolute path and relative path), API jump
06. Page routing
   The routing of all pages in the applet is managed by the framework. The framework maintains all current pages in the form of a stack.
   1. When a routing switch occurs, the page stack behaves as follows
     Routing method: page stack performance
     initialization, new page is pushed into the stack,
     a new page is opened, a new page is pushed
     into the stack, the page redirects the current page out of the stack, and the new page is pushed into the stack,
     and the returned page is continuously popped out of the stack. Until the target returns to the page
     Tab switching All pages are popped out of the stack, leaving only the new Tab Page
     reload All pages are popped out of the stack, leaving only the new page
     Developers can use the getCurrentPages() function to get the current page stack.

   2. Routing method
     For the triggering method of routing and the page life cycle function, please refer to the official website document for details

   Note 1: The stack is a first-in-last-out data structure (bullet folder)
   Note 2: Demonstrate how to specify the page startup (important)
        1. Modify the routing configuration
        2. Add the startup configuration and specify the startup page


##Example 4-1: Add parameters to the route
##Example 4-2: Number auto-increment and auto-decrement (how to pass parameters +1 or -1 in the event)
##Example 4-3: Data two-way binding
07. WeChat applet event binding (important)
   1. Event category:
     tap: click event
     input: input event
     longtap: long press event;
     touchstart: touch start;
     touchend: touch end;
     touchcansce: cancel touch;

     Small program binding value
     1. One-way binding M --> V
                                       setData 
     2. One-way binding actually binds a copy of M ---------> copy --> V


     Note 1: The request processing method in the applet cannot pass parameters. The correct way: pass parameters through the data-xxx attribute, and then get the parameter error through the event source <button bindtap="handletap(-1)"Correct<button
          bindtap
          =
          "
          handletap " data-number="{ {-1}}"

          Positive solution: Passing a fixed value -1 
                data-number="{ {-1}}"
                can also bind the value
                data-number="{ {n}}" 


                 Then get e.currentTarget.dataset.number                 from the event object
          

     Note 2: In the WeChat applet, the js data and the data displayed on the front end are single data streams.
          That is, if the data in js changes, the front end can display it immediately, but if the front end data changes, js cannot be changed, what should I do!


          We can use the bindinput method to achieve two-way data binding.


          Principle: We use the bindinput event to obtain the input value of the input, and then according to the dataset to obtain data binding with the objects in the data array //1 . Define the dataList
          attribute
          in data, and define the two-way binding in it Attribute name
          //2. Define bindInput method
          //3.<input class="input" bindinput="bindInput" data-name="realName" placeholder="Please enter account number" auto-focus/>
            bindInput(e) {               console .log("bindInput");               //debugger               // form two-way data binding               var that = this;               var dataset = e.target.dataset;               // data-begins with custom attributes, which can be obtained through dataset, dataset is a json object               var name = dataset.name;               var value = e.detail.value;







              //Small problem: The data attribute received by the rule can only be called dataList
              that.data.dataList[name] = value; //Change of logic layer data
              // Splicing object attribute names for assigning values ​​to object attributes
              var attributeName = "dataList. " + name;
              that.setData({//View layer data changes
                [attributeName]: value
              });
              console.log(that.data.dataList);
            }
    
   2. Event binding:
     bind binding;
     catch binding; (can prevent event bubbling)
     For example: bind click event bindtap
     page.wxml file

   3. Receive parameters
        Page({           onLoad: function(options) {             //The assignment of Mini Program Data must use the setData method, error: this.Data.title='xxx';              this.setData({               title: options.title             })           }         })






   

## Example 4: Modularization
08. Modularization
   can extract some common code into a separate js file as a module

   Note 1: Refer to utils/util.js to be referenced by logs/logs.js
   Note 2: When defining a module, create and directly define an object 
        //common.js
        module.exports = {           sayHello: function (name) {             console.log(" Hello %s", name);           },           sayGoodbye: function (name) {             console.log("Goodbye %s", name);           }         }; 09. API (important)    The mini-program development framework provides rich WeChat native APIs, It can easily invoke the capabilities provided by WeChat,    such as obtaining user information, local storage, payment functions, etc.    API classification    1. Event monitoring API      APIs starting with on are used to monitor whether an event is triggered, such as: wx.onSocketOpen    2. Synchronous API      APIs ending with Sync are all synchronous APIs, such as wx.setStorageSync







   






     

   3. Asynchronous API
     Most APIs are asynchronous APIs, such as wx.request, wx.login and so on. This type of API interface usually accepts a parameter of Object type,
     which supports specifying the following fields as needed to receive the interface call result


### View layer    
10.wxml (important)
   wxml (WeiXin Markup Language) is a set of labeling languages ​​designed by the framework. Combined with basic components and event systems, the structure of the page can be constructed.
   Small program template syntax
   1. Data binding
   2. List rendering (that is, loop)
     demo example: the use of block tags (exists when writing code, but there is no display when the page is rendered)
   3. Conditional rendering (that is, if)
   demo example: data binding, for, if

   4. Template (different from vue)
     WXML provides a template (template), which can define code fragments in the template and then call them in different places.
     1. Define template
       <template name="msgItem">...</template>
     2. Use template
       <template is="msgItem" data="{ {...item}}"/>
   5. Reference
     WXML to provide two A file reference method import and include


   Note 1: It is very easy to master this content with vue experience ^_^

11.WXSS
   WXSS (WeiXin Style Sheets) is a style language used to describe WXML component styles

   WXSS (WeiXin Style Sheets) is a style language used to describe WXML component styles. WXSS is used to determine how WXML components should be displayed.
   In order to adapt to the vast number of front-end developers, WXSS has most of the features of CSS. At the same time, in order to be more suitable for the development of WeChat applets, WXSS has expanded and modified CSS.
   Compared with CSS, the features of WXSS extension are:
   Size unit
   rpx (responsive pixel): It can be adapted according to the screen width. The specified screen width is 750rpx.
   For example, on iPhone6, the screen width is 375px, and there are 750 physical pixels in total, then 750rpx = 375px = 750 physical pixels, and 1rpx = 0.5px = 1 physical pixel.

   style import

12. WXS (omitted, not important)
     WXS (WeiXin Script) is a set of scripting language for applets, combined with WXML, you can build the structure of the page

Appendix 1: A brief description of the require function 
require(...) is a function used in modular programming in Javascript to load modules.
Suppose there is a math module math.js, you can load it like this
var math = require('math');
Then, you can call the method provided by the module:
var math = require('math');
math.add(2 ,3); // 5


Appendix 2: Solution to Black Screen of WeChat Developer Tools
Note 1: The estimated names under User Data of each person are different, but they are all in the WeappLocalData directory
C:\Users\Administrator\AppData\Local\WeChat Developer Tools\User Data \a8265259807471d9496af75b01f1850f\WeappLocalData


###Appendix 3 The problem of using wechat_devtools_1.03.2009140_x64 version for development can never be solved--20201030
###20201104 Solution: Clear the cache and reopen this project
###
Appendix 3: The definition in app_json was not found The solution to the WXML file corresponding to pages pages-category-index
is a bug in the editor. The solution is, for example, if I want to create an order file, there are two ways to create it: the
first one: create pages directly in app.json /order/order, the editor will automatically create the corresponding folders and files, and will not report an error; the
second method: We manually create the file set order under pages, and create the corresponding files, and then add the corresponding files in app.json path,
but at this time the system will report: The WXML file corresponding to the pages “pages/order/order” defined in app.json was not found, which is very strange.
Then we need to solve it, delete the pages of app.json (remember to backup), then save,
close the editor, open it again, put the path just copied back in, and find that no error is reported, and you can play happily

If successful: the console will display the following information
[sitemap index status prompt] According to the sitemap rule [0], the current page [pages/reg/reg] will be indexed

The WXML file corresponding to the pages "pages/xxx/xxx" defined in app.json was not found. Problem
location:
editor bug

Solution:
1. Clear the about page pages in app.json (remember to backup)
2. Save after clearing
3. Close the WeChat development tool and restart
4. Copy and paste the file configuration back
5. The page is generated successfully


Appendix 4: The difference between this.data and this.setData({}) of the WeChat applet

this.data.xx is used to get the page data object ---------- just the change of js (logic layer) data;
this.setData is used to update the interface ------- - Used to update the view layer.
To sum up: the relationship between this.data and this.setData is that this.setData stores a copy of this.data,
and the interface fetches data from the copy of this.data hosted in this.setData.
So we will not directly update the interface when we change this.data, because the copy in this.setData is still not updated at this time.
For details, please refer to: Materials/06 01.mht~06 03.mht

Guess you like

Origin blog.csdn.net/m0_60375943/article/details/123338876