Code snippet of wechat applet

On October 16, 2021, I was working on a wechat applet recently. The knowledge points encountered in the project will be recorded here and will be continuously updated and supplemented in the near future!

1, Get picture width and height

Refer to the original text for the width and height of the picture

// wxml
<image src="{{imgSrc}}"  bindload="imgLoadFunc" style="width:{{contentImgWidth}}rpx; height:{{contentImgHeight }}rpx;"></image>

// js
    contentImgWidth: 0,
    contentImgHeight: 0,
imgLoadFunc: function(e) {
    var tempWidth = e.detail.width; // Get the actual width of the picture
    var tempHeight = e.detail.height; // Get the actual height of the picture
      contentImgWidth: tempWidth,
      contentImgHeight: tempHeight

2, Click the picture to view it

Refer to the picture and zoom in to see the original text
Refer to the original text for calculating the aspect ratio of the picture

// wxml
<image src="{{imgList[0]}}" bindtap="preview" data-src="{{imgList[0]}}"></image>
<image src="{{imgList[1]}}" bindtap="preview" data-src="{{imgList[1]}}"></image>
<image src="{{imgList[2]}}" bindtap="preview" data-src="{{imgList[2]}}"></image>

// js
  data: {
    imgList: [

  //Preview picture, enlarge Preview
  preview(event) {
    let currentUrl = event.currentTarget.dataset.src
      current: currentUrl, // http link to the currently displayed picture
      urls: // http link list of pictures to preview

3, Get screen width and height

onLoad: function () {
     height: wx.getSystemInfoSync().windowHeight,
     width: wx.getSystemInfoSync().windowWidth

4, Open APP end

See documentation

Note that when the applet is opened from the scene opened by the APP (scene value 1069), the applet will obtain the ability to return to the APP. At this time, the user can click the button to open and pull up the APP of the applet. That is, the applet cannot open any APP, but can only jump back to APP.

5, Remove the return key in the upper right corner

Reference articles

 <view bindtap="gotopost">Another jump mode</view>
    wx.reLaunch({url: "/pages/post/index?id=62"});

6, Subcomponents use global styles

Without this sentence, the style in the applet will be preceded by index –

  options: {
    addGlobalClass: true

7, After iconfont is introduced, the real machine debugging is not displayed

Reference articles

Solution: convert woff, and woff2 files to base64 and use them
Convert web address:

8, Applet UI framework Introduction (vant)

An article in Jianshu:
Installation tutorial on vant official website:

  1. Open the terminal in wechat developer tool, enter npm init, and go all the way ok to generate a new package.json
  2. Refer to the vant official website, NPM I @ vant / Web - s -- production to install the latest version. For the remaining steps, refer to the installation tutorial on the vant official website

Yitong has been configured according to the official website. You can see the development preview and real machine test. When the uploaded code is released into the experience version, there is a blank. What? After searching on the Internet, delete the npm package and reinstall it. Do it again. Build the npm from time to time and solve it after a meal of operation

9, Encapsulation of applet network request method

Applet network request encapsulation:

10, The text box filters letters, leaving only numbers

  //In the input box, enter the triggered function
    var mobile = "";
    var tel = e.detail.value;
    var reg = /[a-zA-Z]+/;
    var result;
    while(result = tel.match(reg)){
      tel = tel.replace(result[0],'');
    //This method is the most convenient. It can filter not only letters, but also other special symbols
    var s ="Price 4500 yuan";
    var num= s.replace(/[^0-9]/ig,"");

11, Applet nested loop

Use Wx: for item = "newitem" to reassign the item name

  <van-index-bar index-list="{{ indexList }}" highlight-color="#f00">
    <view wx:for="{{ zoneList }}" wx:key="index">
      <van-index-anchor index="{{item.key}}" />
      wx:for="{{ item.list }}" 
      value="{{'+' +}}"

12, Upload Avatar

Reference article:

    <!-- head portrait -->
    <view class="avatar-wrap" bindtap="changeAvatar">
        <image class="avatar"  mode="aspectFill" src="{{registerform.avatar}}" ></image>

	// js method
    var that = this;
    var avatarimg = "registerform.avatar"
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        const tempFilePaths = res.tempFilePaths
          url: BASEURL + '/api/common/upload',
          filePath: tempFilePaths[0],
          name: 'file',
          formData: {
            'user': 'test'
          success (res){
            const result = JSON.parse(;
                title: 'Upload failed',


        fail: function () {// fail
        complete: function () {// complete

13, Functions used in WXML

<view>{{ formate(time) }}</view>

Precautions for use:
Reference article:

// In the wxml page, first import the wxs file and then use it
<wxs module="filter" src="../../utils/wxs/common.wxs"></wxs>
<text class="font26">{{ filter.calc(postObj.browse_num) }}browse</text>

//In wxs file
var filter = {
    var total = null;
    if(num > 10000){
      total = (num/10000).toFixed(1) + 'w';
      total = num;
    return total
module.exports = {

14, Regular matching in wxs

Reference article:

Regular method reference:

Wechat official documents:

The regular matching method in js is not supported in wxs. The getRegExp function of wechat should be used.

// wxs file
    var strnew = str + ' ';
    var reg = getRegExp('@([^@\s]*)\s', 'g');
      strnew = strnew.replace(reg,function (match,param,offset,string) {
          var html = "<span style='color:#41AEF5'>" + match +"</span>";
          return html;
      return strnew;
      return str;

// wxml file
<wxs module="filter" src="../../utils/wxs/common.wxs"></wxs>
<view class="mt30 font30">
  <rich-text nodes="{{ filter.replaceStr(item.content) }}"></rich-text>

15, Dynamic setting applet navigationBarTitleText

      title: 'Dynamic title'

16, The navigation bar background color changes as the scroll bar scrolls

Reference article:

<!-- wxml -->
<scroll-view scroll-y="true" style="height: 100%;" bindscroll="scroll">
	<!-- Customize navigation bar -->
	<view class="nav-top" style="padding-top: {{ statusBarHeight }}px; background: {{ navTopBgcolor }}; color:{{navColor}}">
      <view class="nav-top-img-view" bindtap="onBack">
      <!-- <van-icon name="arrow-left" />  -->
      <view class="nav-top-title">Personal home page</view>
      <view class="nav-top-img-view"></view>

// js
  data: {
    statusBarHeight: wx.getSystemInfoSync()['statusBarHeight'],
// The scroll bar scrolls and the title bar changes color
  scroll(e) {
    if (e.detail.scrollTop < 100) {
        navTopBgcolor: 'transparent',
		} else {
        navTopBgcolor: '#fff',

// wxss
/*Top navigation bar*/
  position: fixed;
  top: 0;
	left: 0;
	height: 45px;
	width: 100%;
	/* opacity: .5; */
	display: flex;
  flex-direction: row;
  transition: 0.3s all linear;

.nav-top-img-view {
	height: 45px;
  width: 45px;
  line-height: 45px;
  text-align: center;

.nav-top image {
	height: 20px;
	width: 20px;
	margin: 12.5px;

.nav-top-title {
  transition: 0.3s all linear;
	text-align: center;
	line-height: 45px;
	flex: 1;

17, Encapsulate the selected date component (only month and day are selected, and the current year is the default)

Reference article – calculate the number of days per month:

Reference website – to find out which day of the month is Saturday or Sunday:

Tags: Mini Program

Posted on Sat, 16 Oct 2021 14:40:28 -0400 by SlyOne