WeChat applet learning wxs usage tutorial

WeChat applet learning wxs usage tutorial

What is wxs?

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

wxs Tags

<wxs module="utils" src="../../wxs/test.wxs"></wxs>

module attributes:

The module name of the current tag. It is recommended that this value be unique. If there is a module with the same name, it will be overwritten in order (the latter will overwrite the former).

src attribute:

a. Only .wxs files can be referenced, and the path must be relative;

b. All wxs modules are singletons. When a wxs module is referenced for the first time, it will be automatically initialized as a singleton object. Multiple pages, multiple places, and multiple uses all use the same wxs module object;

c. If a wxs module has not been referenced after being defined, the module will not be parsed and run;

wxs module

wxs code can be written in the tag of wxml file, or in the file with .wxs as suffix (in WeChat developer tool, right click to create .wxs file directly, and write wxs script directly in it)

Writing method 1 is as follows:

//test.wxml
<wxs module="utils">
  module.exports = {
    msg: 'hello world'
  }
</wxs>
<view> {{utils.msg}}</view>
// Screen output: hello world

Writing method 2 is as follows:

//text.wxml
<wxs module="utils" src="../../common/wxs/test.wxs"></wxs>
// You can also use the single tag closure method directly // <wxs module="utils" src="../../common/wxs/test.wxs" />
<view> {{utils.msg}}</view>
//test.wxs
module.exports = {
  msg: 'hello world'
}

It is generally recommended that wxs code be written in a .wxs file.

Module Description

  1. Each .wxs file and wxs tag is a separate module;
  2. Each module has an independent scope, that is, variables and functions defined in a module are private by default and not visible to other modules.
  3. If a module wants to expose its internal private variables and functions, it can only be achieved through module.exports.

Q1: If the same wxml imports multiple wxs files, and there are variables or functions with the same name, what will happen?

//test.wxml
<wxs module="utils" src="../../wxs/test.wxs"></wxs>
<wxs module="utils1" src="../../wxs/test1.wxs"></wxs>
<view> {{utils.msg}} + {{utils.say()}}</view>
<view> {{utils1.msg}} +{{utils1.say()}}</view>

//test.wxs
module.exports = {
  msg: 'hello test.wxs',
  say: function (){
    return 'test.wxs的say()'
  }
}
//test1.wxs
module.exports = {
  msg: 'hello test1.wxs',
  say: function (){
    return 'test1.wxs的say()'
  }
}
// Screen output // hello test.wxs + test.wxs's say()
// hello test1.wxs + test1.wxs's say()

After verification, it is found that each module has an independent scope.

Q2: If you want to import other wxs file modules into a .wxs module, how can you do it?

Through the require function

//test.wxs
var test1 = require('./test1.wxs')
module.exports = {
  msg: 'hello test.wxs',
  say: function (){
    console.log(test1.msg)
    return 'test.wxs的say()'
  }
}
// Console output // [WXS Runtime info] hello test1.wxs 

wxs comments

// wxml file <wxs module="utils">
// .wxs-single-line comment/**
 * .wxs-multi-line comments*/
 
/*
var a = 1

</wxs>

In the above examples, all wxs codes are commented. The third way of writing is relatively rare. I saw it while studying and recorded it.

If it is a .wxs file, there are only two types of comments: single-line and multi-line.

wxs basics

The addition operation (+) is used to concatenate strings;

<wxs module="utils">
module.exports = {
  getnum: function () {
    var a = 10
    var b = 20
    var str = a + '+' + b + '=' + (a+b) 
    return str
  }
}
</wxs>
<view>{{utils.getnum()}}</view>

The `` concatenation operator cannot be used, otherwise an error will be reported.

wxs currently supports the following data types:

number (value), string (string), boolean (Boolean value), array (array), object (object), function (function), date (date), regexp (regular expression)

There is no null/undefined in wxs data types.

To generate a date object, you need to use getDate(), which returns an object of the current time.

<wxs module="utils">
module.exports = {
  getNowTime: function () {
    return getDate()
  }
}
</wxs>
<view>{{utils.getNowTime()}}</view>
// Screen output // Sat May 01 2021 14:42:57 GMT+0800 (China Standard Time)

You cannot use new Date(), an error will be reported.

ES6 syntax is not supported, such as destructuring and arrow functions.

You cannot use let/const to declare variables, you must use var, and there is variable promotion.

<wxs module="utils">
module.exports = {
  getnum: function () {
    let a = 10
    return a
  }
}
</wxs>
<view>{{utils.getnum()}}</view>

Application Scenario

Generally, the backend returns the timestamp format to the frontend, but we need to process it into the desired time format, such as yyyy-mm-dd. In this case, we can use wxs to call the time conversion function.

Maybe someone will ask, isn't it feasible to use a function in js to package the data and then output it to the page? The answer is yes, it's just a matter of pursuing a solution that you think is relatively better.

<wxs module="utils">
module.exports = {
  formatTime: function (timeStamp) {
    var now = getDate(parseInt(timeStamp))
    var year = now.getFullYear()
    var month = now.getMonth()+1 
    month = month < 10 ? '0' + month: month
    var day = now.getDate()
    day = day < 10 ? '0' + day :day
    return year + '-' + month + '-' + day 
  }
}
</wxs>
<view>{{utils.formatTime(1619852841428)}}</view>
// Screen output // 2021-05-01

Sometimes the network image address returned by the background is a relative path, and sometimes it is a complete image path. If you want to display the image, you need to add the configured domain name prefix.

<wxs module="utils">
module.exports = {
  getImg: function (url = '') {
    var origin = 'https://xxx.com'
    if (url.indexOf('https') !== -1 || url.indexOf('http') !== -1) {
      return url
    } else {
      return origin + url
    }
  }
}
</wxs>
<image src="{{utils.getImg('/a.png')}}"></image>
// src output // https://xxx.com/a.png

Pitfall Records

Expected LineFeed appears when calling in wxml using compilation

Solution: Replace all ES6 stuff with ES5 and use var declaration.

Summarize

This is the end of this article about the tutorial on how to use wxs for WeChat mini program learning. For more relevant content on how to use wxs for WeChat mini program, 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 wxs achieves ceiling effect

<<:  How to export and import .sql files under Linux command

>>:  MySQL 5.7.20 free installation version configuration method graphic tutorial

Recommend

How to use HTML+CSS to create TG-vision homepage

This time we use HTML+CSS layout to make a prelim...

JS realizes automatic playback of timeline

Recently, I have implemented such an effect: clic...

Detailed explanation of MySQL transactions and MySQL logs

Transactional Characteristics 1. Atomicity: After...

Three steps to solve the IE address bar ICON display problem

<br />This web page production skills tutori...

Vue+element+oss realizes front-end fragment upload and breakpoint resume

Pure front-end implementation:切片上傳斷點續傳.斷點續傳needs ...

CSS3 frosted glass effect

If the frosted glass effect is done well, it can ...

MySQL/MariaDB Root Password Reset Tutorial

Preface Forgotten passwords are a problem we ofte...

Detailed usage of Linux text search command find

The find command is mainly used to find directori...

Analysis of the principle of Rabbitmq heartbea heartbeat detection mechanism

Preface When using RabbitMQ, if there is no traff...

MySQL 8.0.11 Community Green Edition Installation Steps Diagram for Windows

In this tutorial, we use the latest MySQL communi...

Summary of methods to improve mysql count

I believe many programmers are familiar with MySQ...

Analyze Tomcat architecture principles to architecture design

Table of contents 1. Learning Objectives 1.1. Mas...