WXS(WeiXin Script)是小程序的一套脚本语言,wxs可以说就是为了满足能在页面中使用js存在的,在wxml页面中,只能在插值{{ }}中写简单的js表达式,而不能调用方法,例如想取出一个字符串的最后一位,就不能调用slice()方法。
使用 ①写好wxs文件 然后导出要使用的方法或变量
②在待使用页面 使用<wxs src="/path" module="tools" />引入
③在插值{{}}中使用tools.method_name(para)
例如截取字符串
function my_slice(str,a,b){
return str.slice(a,b);
}
module.exports = {
my_slice: my_slice
}
<wxs src="../../utils/string.wxs" module="tools" />
<view>
{{tools.my_slice("123456789",0,5)}}
</view>
页面使用例子
直接写在需要用的wxml页面上: (这里是时分秒转换)
<wxs module="foo">
module.exports = {
toStr: function(n){
n = Math.floor(n)
return n<10 ? "0"+n : ""+n
}
}
</wxs>
<text class='now'>{{foo.toStr( current/60 )}}:{{foo.toStr( current%60 )}}</text>
<!--current 为数据值-->