WeChat applet 2

WXML template syntax

data binding

① Define data in data

In the .js file corresponding to the page, define the data into the data object

② Using data in WXML

Bind the data in data to the page for rendering, and use Mustache syntax (double braces) to wrap variables.

Application Scenarios of Mustache Grammar

  1. binding content

    // js
    Page({
        data: {
            msg:'hello'
        },
    })
    
    // wxml
    <view><text>{{msg}}</text></view>
    
  2. bind property

    // js
    Page({
        data: {
            imgsrc:'./imgs/hello.png'
        },
    })
    
    // wxml
    <image src="{{imgsrc}}"></image>
    
  3. Operations (ternary operations, arithmetic operations, etc.)

    // js
    Page({
        data: {
            randomNum:Math.random().toFixed(2)
        },
    })
    
    // wxml
    <text>{{ randomNum * 100 }}</text>
    <text>{{ randomNum * 100 > 50 ? 'greater than 50' : 'Less than or equal to 50' }}</text>
    

event binding

Events commonly used in applets

typebinding methodevent description
tapbindtap or bind:tapThe finger leaves immediately after touching, similar to the click event in HTML
inputbindinput or bind:inputinput event for textbox
changebindchange or bind:changeTriggered when the state changes

Event binding bindtap touch event

In the applet, there is no onclick mouse click event in HTML, but the tap event is used to respond to the user's touch behavior.

  1. Through bindtap, the tap touch event can be bound to the component, the syntax is as follows:

    // Note: do not add () after btnTapHandler
    <button type="primary" bindtap="btnTapHandler">button</button>
    
  2. Define the corresponding event processing function in the .js file of the page, and the event parameters are received through the formal parameter event (generally abbreviated as e)

    Page({   
        btnTapHandler(e) {
            console.log(e);
        },
    })
    

event object event

When the event callback is triggered, an event object event will be received, and its detailed properties are shown in the following table:

Attributestypeillustrate
typeStringevent type
timeStampIntegerThe number of milliseconds elapsed since the page was opened until the event was triggered
targetObjectA collection of some property values ​​of the component that triggered the event
currentTargetObjectA collection of some property values ​​of the current component
detailObjectadditional information
touchesArrayTouch event, an array of touch point information currently on the screen
changedTouchesArrayTouch event, an array of currently changing touch point information

event.target and event.currentTarget

By default, the event spreads outward in a bubbling manner. event.target is the source component that triggers the event, and event.currentTarget is the outer component that wraps the source component.

// wxml
<view id="view" bindtap="viewTap">
    <button id="btn" type="primary" bindtap="btnTap">button</button>
</view>
// js
Page({
    viewTap(e) {
        console.log('clicked view');
        console.log(e.target.id);
        console.log(e.currentTarget.id);
    }    
    btnTap(e) {
        console.log('clicked the button');
        console.log(e.target.id);
        console.log(e.currentTarget.id);
    },
})

Print after button click:

clicked the button
btn
btn
 clicked view
btn
view

Print after clicking view:

clicked view
view
view

Responsive data update Call this.setData(dataObject) method

In WXML, ordinary property bindings are one-way.

<text>{{msg}}</text>

<button id="btn" type="primary" bindtap="btnTap">button</button>
Page({
    data: {
        msg: 'hello',
    },
    btnTap() {
        console.log(this.data.msg); // hello
        this.data.msg = 'hello'
        console.log(this.data.msg); // Hello, Note: The data is changed at this time, but the view display is still hello
    }
})

If you want to update the data view synchronously, you need to call this.setData(dataObject) method

Page({
    data: {
        msg: 'hello',
    },
    btnTap() {
        console.log(this.data.msg); // hello
        this.setData({msg:'hello'})
        console.log(this.data.msg); // Hello Note: At this time, both the data and the view are changed to: Hello
    }
})

Event parameter data-parameter name="{{parameter value}}"

The event parameter passing method of the applet is quite special, and it cannot be like js. After binding the event, add parentheses after the event name to carry the parameters, for example:

// Writing this way will report an error:
// Component "pages/list/list" does not have a method "btnTap(11)" to handle event "tap".
<button id="btn" type="primary" bindtap="btnTap(11)">button</button>

Because the applet will treat the attribute value of bindtap as an event name, which is equivalent to calling an event processing function named btnTap(11).

If you want to implement event parameter passing in the WeChat applet, you can use data-* custom attributes to pass parameters, where * represents the name of the parameter

<button bindtap="btnTap" data-aaa="{{5}}">Pass parameter, the parameter name is aaa,The parameter value is 5</button>

Get passed parameters event.target.dataset.parameter name

In the event processing function, the value of the specific parameter can be obtained through event.target.dataset.parameter name

btnTap(e) {
    // e.target.dataset is an object that contains all the parameters passed through data-* to
    console.log(e.target.dataset.aaa);
}

bindinput text box input event

The input event of the text box is bound by bindinput

<input type="text" bindinput="inputHandler" />
inputHandler(e) {
    console.log(e.detail); // {value: "13", cursor: 2, keyCode: 99}
    // e.detail.value is the new value of the text box after the change
    console.log(e.detail.value); // 13
}

Realize data synchronization between the text box and data

<text>{{inputValue}}</text>
<input type="text" value="{{inputValue}}" bindinput="inputHandler"/>
Page({
    data: {
        inputValue: ''
    },
    inputHandler(e) {
        // Modify the value in data by this.setData()
        this.setData({
            inputValue: e.detail.value // e.detail.value is the new value of the text box after the change
        })
    }
})

conditional rendering

wx:if wx:elif wx:else

  • In the applet, use wx:if="{{condition}}" to determine whether the code block needs to be rendered

    <view wx:if="{{isShow}}">content</view>
    
  • You can also use wx:elif and wx:else to add else judgment

    <view wx:if="{{num>10}}">greater than 10</view>
    <view wx:elif="{{num==10}}">equal to 10</view>
    <view wx:else>less than 10</view>
    

Use wx:if with <block>

If you want to control the display and hiding of multiple components at once, you can use a <block> tag to wrap multiple components, and use the wx:if control attribute on the <block> tag

Note: <block> is not a component, it is just a wrapping container and will not be rendered on the page.

<block wx:if="{{true}}">
    <view>component 1</view>
    <view>component 2</view>
</block>

hidden

In the applet, directly using hidden="{{ condition }}" can also control the display and hiding of elements

<view hidden="{{true}}">The condition is true hide, false show</view>

wx:if vs. hidden

  • wx:if controls the display and hiding of elements by dynamically creating and removing elements
  • hidden controls the display and hiding of elements by switching styles (display: none/block;)

When switching frequently, it is recommended to use hidden

When the control conditions are complex, it is recommended to use wx:if with wx:elif, wx:else to switch between display and hide

list rendering

wx:for

Through wx:for, the repeated component structure can be rendered in a loop according to the specified array

by default,

  • The index of the current loop item is represented by index;

  • The current loop item is represented by item.

Use of wx:key

Similar to :key in Vue list rendering, when the applet implements list rendering, it is also recommended to specify a unique key value for the rendered list items, so as to improve rendering efficiency

The value of wx:key: a string, representing a certain property of the item in the array of the for loop. The value of this property needs to be the only string or number in the list, and cannot be changed dynamically.

data: {
    userList:[
        {id:1,name:'Zhang San',age:20},
        {id:2,name:'Li Si',age:21},
        {id:3,name:'Wang Wu',age:22},
    ]
},
<view wx:for="{{userList}}" wx:key="id">
id: {{item.id}},Name:{{item.name}},age:{{item.age}}
</view>

WXSS template styles

WXSS (WeiXin Style Sheets) is a style language for beautifying WXML component styles, similar to CSS in web development.

WXSS has most of the features of CSS. At the same time, WXSS also expands and modifies CSS to adapt to the development of WeChat applets.

Compared with CSS, the features of WXSS extensions are:

  • rpx unit of measure
  • @import style import

rpx unit of measure

rpx (responsive pixel) is unique to WeChat applets, and is used to solve the size unit of screen adaptation.

The realization principle of rpx

The implementation principle of rpx is very simple:

In view of the different screen sizes of different devices, in order to achieve automatic screen adaptation, rpx divides the screens of all devices into 750 equal parts in width (that is, the total width of the current screen is 750rpx).

  • On smaller devices, 1rpx represents a smaller width
  • On larger devices, 1rpx represents a larger width

When the applet is running on different devices, it will automatically convert the rpx style unit into the corresponding pixel unit for rendering, so as to achieve screen adaptation.

Unit conversion between rpx and px

On iPhone6, the screen width is 375px, and there are a total of 750 physical pixels, which are equally divided into 750rpx. but:
750rpx = 375px = 750 physical pixels

​ 1rpx = 0.5px = 1 physical pixel

equipmentConvert rpx to px (screen width/750)Convert px to rpx (750/screen width)
iPhone51rpx = 0.42px1px = 2.34rpx
iPhone61rpx = 0.5px1px = 2rpx
iPhone6 Plus1rpx = 0.552px1px = 1.81rpx

Official suggestion: When developing WeChat applets, designers can use iPhone6 ​​as the standard for visual drafts.

Development example: If you want to draw a box with a width of 100px and a height of 20px on the iPhone6, the width and height are 200rpx and 40rpx respectively when converted into rpx units.

style import

Out-of-line style sheets can be imported using the @import syntax provided by WXSS.

The syntax of @import

@import is followed by the relative path of the external style sheet to be imported, and the statement ends with ;.

@import "./common.wxss"

Global and local styles

The style defined in app.wxss is a global style, acting on every page

The styles defined in the page's .wxss file are local styles, which only apply to the current page.

Notice:

① When the local style conflicts with the global style, according to the principle of proximity, the local style will override the global style

②When the weight of the local style is greater than or equal to the weight of the global style, the global style will be overwritten

global configuration

The app.json file in the root directory of the applet is the global configuration file of the applet.

Commonly used configuration items are as follows:

  • pages

    Record the storage path of all pages of the current applet

  • window

Globally set the appearance of the applet window

  • tabBar

Set the tabBar effect at the bottom of the applet

  • style

Whether to enable the new version of the component style

"style": "v2" means to enable the new version of the style, delete the diversion configuration means to use the old version of the style

// app.json
{
    "pages": [
        "pages/list/list",  // The first item defaults to the home page
        "pages/index/index",
        "pages/logs/logs"
    ],
	"window": {
        "navigationBarBackgroundColor": "#269646", // The background color of the navigation bar
        "navigationBarTitleText": "My WeChat Mini Program", // title of the navigation bar
        "navigationBarTextStyle": "white", // Navigation bar title color black/white
        "enablePullDownRefresh": true, // Enable the pull-to-refresh function globally
        "backgroundColor": "#eee", // The background color of the window when pulling down to refresh
        "backgroundTextStyle": "light" // The loading style when pulling down to refresh is only light/dark
	},
    "tabBar": {
        "list": [{
                "pagePath": "pages/index/index",
                "text": "index home page"
            },
            {
                "pagePath": "pages/list/list",
                "text": "list List"
            }
        ]
    },
    "style": "v2", // Whether to enable the new version of the component style
    "sitemapLocation": "sitemap.json",
    "lazyCodeLoading": "requiredComponents"
}

Global Configuration - window s

Components of an applet window

Commonly used configuration items for window nodes:

attribute nametypeDefaultsillustrate
navigationBarTitleTextStringstringNavigation bar title text content
navigationBarBackgroundColorHexColor#000000Navigation bar background color, such as #000000
navigationBarTextStyleStringwhiteNavigation bar title color, only black / white is supported
backgroundColorHexColor#ffffffbackground color of the window
backgroundTextStyleStringdarkThe style of the drop-down loading, only supports dark / light
enablePullDownRefreshBooleanfalseWhether to enable pull-down refresh globally
onReachBottomDistanceNumber50The distance from the bottom of the page when the page pull bottom event is triggered, in px
// app.json -> window default configuration
"window": {
    "navigationBarBackgroundColor": "#fff", // The background color of the navigation bar
    "navigationBarTitleText": "weixin",  // title of the navigation bar
    "navigationBarTextStyle": "black" // Navigation bar title color black/white
},

Revise:

"window": {
    "navigationBarBackgroundColor": "#269646",
    "navigationBarTitleText": "My WeChat Mini Program",
    "navigationBarTextStyle": "white"
},

Globally enable the pull-down refresh function enablePullDownRefresh

Concept: pull-down refresh is a proper term for mobile terminals, which refers to the behavior of reloading page data by sliding your finger down on the screen.

Setting steps: app.json -> window -> set the value of enablePullDownRefresh to true

Note: Enabling the pull-to-refresh function in app.json will affect every applet page!

The background color of the window when pulling down to refresh backgroundColor

Default is white

The loading style backgroundTextStyle when pulling down to refresh

The default is light color light, the only available values ​​are light and dark

The bottom distance of the pull-up onReachBottomDistance

Pulling up and touching the bottom is a proper term for the mobile terminal. It is the behavior of loading more data by pulling up and sliding the finger on the screen.

Note: The default distance is 50px. If there is no special requirement, it is recommended to use the default value.

Global configuration - tabBar

tabBar is a common page effect in mobile applications, and it is used to achieve fast switching between multiple pages.

Small programs are usually divided into:

  • bottom tabBar

  • top tabBar

Notice:

  • Only a minimum of 2 and a maximum of 5 tabs can be configured in the tabBar
  • When rendering the top tabBar, the icon is not displayed, only the text is displayed

6 components of tabBar

  1. backgroundColor: the background color of the tabBar
  2. selectedIconPath: the image path when selected
  3. borderStyle: the color of the border on the tabBar
  4. iconPath: the path of the image when it is not selected
  5. selectedColor: the color of the selected text on the tab
  6. color: the default (unselected) color of the text on the tab

Configuration items of the tabBar node

AttributestyperequiredDefaultsdescribe
positionStringnobottomThe position of the tabBar, only supports bottom/top
borderStyleStringnoblackThe color of the upper border of the tabBar, only black/white is supported
colorHexColornoThe default (unselected) color of the text on the tab
selectedColorHexColornoThe color of the text on the tab when selected
backgroundColorHexColornobackground color of tabBar
listArrayYesA list of tabs, with a minimum of 2 and a maximum of 5 tabs

Configuration options for each tab item

Attributestyperequireddescribe
pagePathStringYesPage path, the page must be pre-defined in pages
textStringYesthe text displayed on the tab
iconPathStringnoThe path of the icon when it is not selected; when the postion is top, the icon is not displayed
selectedIconPathStringnoThe icon path when selected; when the postion is top, the icon is not displayed
// app.json

{
    "pages": [        
        "pages/index/index",
        "pages/list/list",
        "pages/logs/logs"
    ],
    "window": {
        "navigationBarBackgroundColor": "#269646",
        "navigationBarTitleText": "My WeChat Mini Program",
        "navigationBarTextStyle": "white",
        "enablePullDownRefresh": true,
        "backgroundColor": "#eee",
        "backgroundTextStyle": "light"
    },
    "tabBar": {
        // list is a required item for configuring tabBar, indicating the list of tabs, 2-5 items
        "list": [
            {
                "pagePath": "pages/index/index",  // page path
                "text": "index home page"  // the text displayed on the tab   
            },
            {
                "pagePath": "pages/list/list",
                "text": "list List"
            }
        ]
    },
    "style": "v2",
    "sitemapLocation": "sitemap.json",
    "lazyCodeLoading": "requiredComponents"
}

Case: configure tabBar

// app.json

{
    "pages": [
        "pages/home/home",
        "pages/message/message",
        "pages/contact/contact"
    ],
    "window": {
        "navigationBarBackgroundColor": "#269646",
        "navigationBarTitleText": "My WeChat Mini Program",
        "navigationBarTextStyle": "white",
        "enablePullDownRefresh": true,
        "backgroundColor": "#eee",
        "backgroundTextStyle": "light"
    },
    "tabBar": {
        "position": "bottom", // The default is the bottom tabBar can be set to top
        "list": [{
                "pagePath": "pages/home/home",
                "text": "front page",
                "iconPath": "./imgs/home.png",
                "selectedIconPath": "./imgs/home-active.png"
            },
            {
                "pagePath": "pages/message/message",
                "text": "information",
                "iconPath": "./imgs/message.png",
                "selectedIconPath": "./imgs/message-active.png"
            },
            {
                "pagePath": "pages/contact/contact",
                "text": "contact us",
                "iconPath": "./imgs/contact.png",
                "selectedIconPath": "./imgs/contact-active.png"
            }
        ]
    },
    "style": "v2",
    "sitemapLocation": "sitemap.json",
    "lazyCodeLoading": "requiredComponents"
}

page configuration

In the applet, each page has its own .json configuration file, which is used to configure the window appearance and page effects of the current page.

The relationship between page configuration and global configuration

In the applet, the window node in app.json can globally configure the window performance of each page in the applet.

If some applet pages want to have special window performance, at this time, the "page-level .json configuration file" can meet this requirement.

Note: When the page configuration conflicts with the global configuration, according to the nearest principle, the final effect is subject to the page configuration.

Commonly used configuration items in page configuration

Like the window configuration item (app.json), you can configure the following:

AttributestypeDefaultsdescribe
navigationBarBackgroundColorHexColor#000000Current page navigation bar background color, such as #000000
navigationBarTextStyleStringwhiteCurrent page navigation bar title color, only black/white is supported
navigationBarTitleTextStringCurrent page navigation bar title text content
backgroundColorHexColor#ffffffThe background color of the current page window
backgroundTextStyleStringdarkThe current page drop-down loading style, only supports dark / light
enablePullDownRefreshBooleanfalseWhether to enable pull-to-refresh effect for the current page
onReachBottomDistanceNumber50The distance from the bottom of the page when the page pull bottom event is triggered, the unit is px

network data request

Limitations on network data requests in applets

For security reasons, the Mini Program officially imposes the following two restrictions on data interface requests:

  1. Only HTTPS type interfaces can be requested
  2. The domain name of the interface must be added to the trust list

Configure request legal domain name

Requirement description: Assume that in your own WeChat applet, you want to request the interface under the https://www.escook.cn/ domain name

Configuration steps: log in to the WeChat applet management background https://mp.weixin.qq.com/ -> Development -> Development Settings -> Server Domain Name -> Modify the legal domain name of the request

Precautions:

  • The domain name only supports the https protocol
  • Domain names cannot use IP addresses or localhost
  • The domain name must be registered with ICP
  • The server domain name can apply for up to 5 revisions within one month

After configuration, you can see the setting content of the legal domain name in WeChat Developer Tools = "Details =" Project Settings = "Domain Name Information

Make a GET request

Call the wx.request() method provided by the WeChat applet to initiate a GET data request

Make a POST request

Call the wx.request() method provided by the WeChat applet to initiate a POST data request

Request data when the page just loads

In many cases, we need to automatically request some initialization data when the page is just loaded. At this point, you need to call the function to get the data in the onLoad event of the page

Skip request valid domain name verification

If the back-end programmer only provides the interface of the http protocol, but does not provide the interface of the https protocol for the time being.

At this time, in order not to delay the development progress, we can temporarily enable the "Development environment does not verify the requested domain name, TLS version, and HTTPS certificate" option in the WeChat developer tools to skip the verification of the legal domain name of the request.

Notice:

The option to skip the valid domain name verification of the request is only used in the development and debugging phase!

A note on cross-domain and Ajax

  • Cross-origin issues only exist in browser-based Web development.

    Since the host environment of the applet is not a browser, but a WeChat client, there is no cross-domain problem in the applet.

  • The core of Ajax technology is to rely on the XMLHttpRequest object in the browser,

    Since the host environment of the Mini Program is the WeChat client, the Mini Program cannot be called "initiating an Ajax request", but "initiating a network data request".

Tags: Front-end Javascript Mini Program

Posted by kida462 on Sun, 27 Nov 2022 03:51:08 +1030