In wechat applets development (native WXML, WXCSS), you want to call methods directly in {{}} to process data, but an error will be reported. For example: in the project involved in the calculation of percentage, JS floating point number operation will have accuracy problems, resulting in too many decimal places, so I want to deal with the value in the template syntax accordingly.

1. Use

< view > ${{(money * 0.03). ToFixed (2)}} fee rate (3%) < / view >Copy the code

Error, cannot use directly, cannot call method in JS.

2. Solutions

{{}} can’t call a function in JS. Wechat put forward a new concept, WXS(WeiXin Script), a set of scripting language for small programs, which can be called in WXML {{}}. WXS methods.

Let’s create a new.wxs file

// Support es4 syntax var filter = {numberToFixed: Module. exports = {numberToFixed: filter.numberTofixed} function(value){return value.tofixed (2)}} // Exports module.exports = {numberToFixed: filter.numberTofixed}Copy the code

Importing files in.wxml:

<! < WXS module="filter" SRC ="./numberToFixed. WXS "></ WXS >Copy the code

Call the method in the. WXS module in {{}} :

<view>¥{{filter. NumberToFixed (money*0.03)}}Copy the code


From vUE to applets, the biggest feeling of page writing is that some of the methods that vUE used to do with computed or methods can be invoked directly in {{}}, which makes it easy to process some data. Wechat launched WXS is also to make up for the small program {{}} can not directly use the method in JS deficiency. On the other hand, it also improves the performance of small programs.