wxs role
The wxml template syntax does not support function calls. If you need to make function calls directly in wxml template syntax, then use wxs syntax to achieve
Precautions for using wxs
- Does not support ES6 syntax
- Unable to call the API of the WeChat applet
- Scripts written in JavaScript in Page/App cannot be invoked
- Module exports must use the CJS specification
How to use wxs
- Method 1: Independent
.wxs
file - Method 2: Use embedded
<wxs>
tags inside .wxml
wxs usage method one
write wxs
script
// /tools/formatTime.wxs
// 格式化时间
var padLeft = function(time) {
time = time + '' // 转换成字符串 可以调用字符串API
return ('00'+time).slice(time.length)
}
// 时间转换
var calcTime = function(time) {
var minutes = Math.floor(time / 60)
var seconds = Math.floor(time) % 60
return padLeft(minutes) + ':' + padLeft(seconds)
}
// wxs不支持ES6语法 必须完整
module.exports = {
calcTime:calcTime
}
import wxs script
指定module属性
<wxs src="/tools/formatTime.wxs" module="formatTime"></wxs>
data
Page({
data: {
musicToalTime: 232,
})
Use the API provided by the module
<view>{
{formatTime.calcTime(musicToalTime)}}</view>
Effect
wxs usage method two
business layer data
// pages/index/index.js
Page({
data: {
shoppingCar:[
{
id:'001',name:'舒肤佳净透啫喱沐浴露',count:2,price:44.90 },
{
id:'002',name:'iphone14pro',count:1,price:8899.00 },
]
}
})
view layer
// pages/index/index.wxml
// wxs脚本
<wxs module="formatPrice">
var addRmb = function(price) {
return '¥' + price
}
var totalPrice = function(shooping) {
return addRmb(shooping.reduce(function (pre,item) {
return pre + item.count * item.price
},0).toFixed(2))
}
module.exports = {
totalPrice: totalPrice
}
</wxs>
<view>{
{
formatPrice.totalPrice(shoppingCar)}}</view>