Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

WeChat widget WXS


May 18, 2021 WeChat Mini Program Development Document


Table of contents


WXS

WXS (WeiXin Script) is a scripting language for small programs that, combined with WXML, can structure pages.

Attention:

  1. wxs does not depend on the underlying library version of the runtime and can run in all versions of the widget.
  2. wxs and javascript are different languages, have their own syntax, and are not consistent with javascript.
  3. The operating environment of wxs and other javascript code are isolated, and functions defined in other javascript files cannot be called in wxs, nor can the APIs provided by small programs be called.
  4. The wxs function cannot be an event callback for a component.
  5. Wxs in small programs on iOS devices can be 2 to 20 times faster than javascript code due to differences in the operating environment. There is no difference in operational efficiency on android devices.

Here are some simple examples of using WXS:

Page rendering

<!--wxml-->
<wxs module="m1">
var msg = "hello world";

module.exports.message = msg;
</wxs>

<view> {{m1.message}} </view>

Page output:

hello world

Data processing

// page.js
Page({
  data: {
    array: [1, 2, 3, 4, 5, 1, 2, 3, 4]
  }
})
<!--wxml-->
<!-- 下面的 getMax 函数,接受一个数组,且返回数组中最大的元素的值 -->
<wxs module="m1">
var getMax = function(array) {
  var max = undefined;
  for (var i = 0; i < array.length; ++i) {
    max = max === undefined ? 
      array[i] : 
      (max >= array[i] ? max : array[i]);
  }
  return max;
}

module.exports.getMax = getMax;
</wxs>

<!-- 调用 wxs 里面的 getMax 函数,参数为 page.js 里面的 array -->
<view> {{m1.getMax(array)}} </view>

Page output:

5