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

MySQL time type selection

Table of contents DATETIME TIMESTAMP How to choos...

MySQL 8.0.24 installation and configuration method graphic tutorial

This article shares the installation tutorial of ...

Detailed explanation of the adaptive adaptation problem of Vue mobile terminal

1. Create a project with vue ui 2. Select basic c...

Why should MySQL fields use NOT NULL?

I recently joined a new company and found some mi...

Implementation of waterfall layout + dynamic rendering

Table of contents Typical waterfall website Water...

How can MySQL effectively prevent database deletion and running away?

Table of contents Safe Mode Settings test 1. Upda...

Summary of Linux sftp command usage

sftp is the abbreviation of Secure File Transfer ...

Some functions of using tcpdump to capture packets in the Linux command line

tcpdump is a flexible and powerful packet capture...

js to make a simple calculator

This article shares the specific code of making a...

How to install openjdk in docker and run the jar package

Download image docker pull openjdk Creating a Dat...

MySQL database operations and data types

Table of contents 1. Database Operation 1.1 Displ...

Vue's guide to pitfalls using throttling functions

Preface In a common business scenario, we need to...

Nginx configures the same domain name to support both http and https access

Nginx is configured with the same domain name, wh...