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

Summary of common knowledge points required for MySQL

Table of contents Primary key constraint Unique p...

Detailed explanation of Vite's new experience

What is Vite? (It’s a new toy on the front end) V...

How to use Vue3 to achieve a magnifying glass effect example

Table of contents Preface 1. The significance of ...

The latest virtual machine VMware 14 installation tutorial

First, I will give you the VMware 14 activation c...

CSS performance optimization - detailed explanation of will-change usage

will-change tells the browser what changes will h...

Some understanding of absolute and relative positioning of page elements

From today on, I will regularly organize some smal...

How to extend Vue Router links in Vue 3

Preface The <router-link> tag is a great to...

MySQL 5.5.27 installation graphic tutorial

1. Installation of MYSQL 1. Open the downloaded M...

How to detect file system integrity based on AIDE in Linux

1. AIDE AIDE (Advanced Intrusion Detection Enviro...

Complete steps to use vue-router in vue3

Preface Managing routing is an essential feature ...

How to use CocosCreator object pool

Table of contents Preface: Specific operations St...

centos 7 modify sshd | prohibit root login and sshd port script definition

1. Create a new user wwweee000 [root@localhost ~]...

Docker container log analysis

View container logs First, use docker run -it --r...

js to achieve simple calendar effect

This article shares the specific code of js to ac...