Summary of common functions and usage methods of WeChat applet development

Summary of common functions and usage methods of WeChat applet development

Here, I have mainly sorted out some commonly used functional points in the development process of small programs, which are very practical. Let's take a look at them.

1. Get height and width

var windowHeight = wx.getSystemInfoSync().windowHeight
var windowWidth = wx.getSystemInfoSync().windowWidth

2. Dynamic binding style and class

class="operBtn {{select==1?'activeClass':''}}"
style="display:{{displayPhoto}}"

3. wx:if

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

4. Click event

<van-tag plain style="margin-left:10px;" bindtap="toggle">Select All</van-tag>
//Bubbling event catchtap for click event<van-button class="shop-but" size="mini" icon="like-o" catchtap="getWish" data-pro_id='{{item.product_id}}'></van-button>

//Get click data let id = e.currentTarget.dataset.id

5. wx:for

//Use the wx:for control attribute on the component to bind an array, and then you can use the data of each item in the array to repeatedly render the component.
//The default subscript variable name of the current item in the array is index, and the default variable name of the current item in the array is item
<view wx:for="{{array}}">
  {{index}}: {{item.message}}
</view>

//Or//Use wx:for-item to specify the variable name of the current element of the array,
//Use wx:for-index to specify the variable name of the current index of the array:
<view wx:for="{{array}}" wx:for-index="idx" wx:for-item="itemName">
  {{idx}}: {{itemName.message}}
</view>

6. Data in data

//Storage this.setData({
        result: event.detail
      });
 //Use this.data.result

7. Modify the page configuration. You can pull down to refresh; modify the page title

"enablePullDownRefresh": true,
"navigationBarBackgroundColor": "#FFA500",
"navigationBarTitleText": "My Invoice",
"navigationBarTextStyle": "white"

8. Dynamically modify page title

wx.setNavigationBarTitle({
     title: this.data.info.name
})

9. Horizontal line

<van-divider custom-style="margin:10px 0;" />

10. WXS (WeiXin Script) is a scripting language for small programs. Combined with WXML, it can build the structure of the page.

//Time format <wxs module="format">
    var format = function(date) {
        var date = getDate(date)
        var year = date.getFullYear()
        var month = date.getMonth() + 1
        var day = date.getDate()
        var weekDay = date.getDay()
        var week = ''
        switch(weekDay){ 
            case 0: 
                week = 'Sunday'
                break; 
            case 1:
                week = 'Monday'
                break; 
            case 2: 
                week = 'Tuesday'
                break; 
            case 3: 
                week = 'Wednesday'
                break; 
            case 4: 
                week = 'Thursday'
                break; 
            case 5: 
                week = 'Friday'
                break; 
            case 6: 
                week = 'Saturday'
                break; 
        }
        return month + '月' + day + '日' + ' ' + week;
    }
module.exports.format = format;
</wxs>


//Put asterisks on mobile mailbox<wxs module="phone">
var toHide = function(array) {
  var mphone = array.substring(0, 3) + '****' + array.substring(7);
  return mphone;
}
module.exports.toHide = toHide;
</wxs>

11. video, attribute usage

<video 
      id="myVideo" 
      src="{{url}}" 
      binderror="videoErrorCallback" 
      show-center-play-btn='{{false}}' 
      show-play-btn="{{true}}"
      Controls
      title="Course"
      object-fit="fill"
      enable-auto-rotation="true"
      bindtimeupdate="bindtimeupdate"
    ></video>
//

 let videoCtx = wx.createVideoContext('myVideo', this)
videoCtx.pause()


//bindtimeupdate Get progress time, limit playback operation according to time bindtimeupdate:function(res){//Playing function, check current playback time, etc. let video_status = this.data.video_status
        let that = this
        if (res.detail.currentTime > 10) {
            if (video_status === '0') {
                wx.showModal({
                    title: 'Login',
                    content: 'The trial course is over. If you want to continue viewing, please log in first',confirmText:'Confirm',
                    success (res) {
                      if (res.confirm) {
                        wx.switchTab({
                            url: '/pages/user/user'
                        })
                      } else if (res.cancel) {
                        wx.navigateBack({
                          delta: 1,
                        })
                      }
                    }
                })
            } else if (video_status === '2'){
                let videoCtx = wx.createVideoContext('myVideo', this)
                videoCtx.pause()
                wx.showModal({
                    title: 'Purchase Course',
                    content: 'The trial course is over. If you want to continue viewing, please purchase first', confirmText: 'Pay now',
                    success (res) {
                    if (res.confirm) {
                        that.onClickButton()
                    } else if (res.cancel) {
                        wx.navigateBack({
                        delta: 1,
                        })
                    }
                    }
                })
            }
            
        } else {
            
        }
    },

12. Data Storage

//save try {
          wx.setStorageSync('car', info)
        catch (e) { }
//Get try {
      var value = wx.getStorageSync('car')
      if (value) {
        this.setData({
          ApplyContent:value
        })
      }
    } catch (e) {
    }

13. Map Usage

//Official website const QQMapWX = require('../../assets/js/qqmap-wx-jssdk')
const qqmapsdk = new QQMapWX({
    key: 'XSTBZ-G74CJ-7BVFQ-KC2JD-ONRK5-ZABGU'
})

getAddressLocation(){
        let that = this
        wx.getLocation({
        type: 'gcj02',
        success (res) {
            const latitude = res.latitude
            const longitude = res.longitude
            that.getAddress(latitude, longitude)
            
        }
        })
    },
    getAddress(latitude, longitude) {
        let that = this
        qqmapsdk.reverseGeocoder({
            location: {latitude,longitude},
            success(res) {
                console.log(res);
                var mks = []
                mks.push({ // Get the returned result and put it in the mks array title: res.result.address,
                    id: 1,
                    latitude: latitude,
                    longitude: longitude,
                    iconPath: "../../img/mk.png", //icon path width: 20,
                    height: 20
                })
                that.setData({
                    address:res.result.address,
                    markers: mks,
                    latitude: latitude,
                    longitude: longitude,
                })
            }
        })
    },

14. Click Copy

copyBtn: function (e) {
        var currentidx = e.currentTarget.dataset.num;
        console.log(currentidx); 
        wx.setClipboardData({
        data: currentidx,
        success: function (res) {
            wx.showToast({
            title: 'Copy Success',
            });
        }
        });
    },

Summarize

This is the end of this article about the common functions and usage methods of WeChat applet development. For more relevant content on common functions of WeChat applet development, please search for previous articles on 123WORDPRESS.COM or continue to browse the related articles below. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • WeChat applet development tool shortcut key summary
  • Detailed explanation of WeChat applet development (project from scratch)
  • Summary of 40 technical tips for WeChat applet development (recommended)
  • WeChat Mini Program Development - Getting Started Tutorial
  • WeChat Mini Program Cloud Development Detailed Tutorial
  • Using WeChat Mini Programs to Develop Front-End [Quick Start]
  • WeChat applet development experience summary (recommended)
  • WeChat Mini Program Development Basic Tutorial

<<:  HTML Language Encyclopedia

>>:  Enable sshd operation in docker

Recommend

CentOS 7 installation and configuration tutorial under VMware10

If Ubuntu is the most popular Linux operating sys...

MySQL 5.7.18 installation tutorial and problem summary

MySQL 5.7.18 installation and problem summary. I ...

MySQL stored procedure in, out and inout parameter examples and summary

Stored Procedures 1. Create a stored procedure an...

Detailed explanation of HTML onfocus gain focus and onblur lose focus events

HTML onfocus Event Attributes Definition and Usag...

Getting Started with CSS3 Animation in 10 Minutes

Introduction Animation allows you to easily imple...

Example code for implementing beautiful clock animation effects with CSS

I'm looking for a job!!! Advance preparation:...

HTML left, center, right adaptive layout (using calc css expression)

In the latest HTML standard, there is a calc CSS e...

About the problem of vertical centering of img and span in div

As shown below: XML/HTML CodeCopy content to clip...

Vue integrates Tencent Map to implement API (with DEMO)

Table of contents Writing Background Project Desc...

A summary of the reasons why Mysql does not use date field index

Table of contents background explore Summarize ba...

Optimization of MySQL thread_stack connection thread

MySQL can be connected not only through the netwo...

How to use vue-cli to create a project and package it with webpack

1. Prepare the environment (download nodejs and s...

Use of filter() array filter in JS

Table of contents 1. Introduction 2. Introduction...

Solve the problem of docker pull image error

describe: Install VM under Windows 10, run Docker...