小程序脚本语言–WXS

在 wxml 中无法调用在页面 .js 中定义的函数,而 wxml 可以调用 wxs 中定义的函数

wxs 脚本文件常作为过滤器,搭配 Mustache 语法使用
wxs 脚本文件不能调用小程序提供的 API

WXS 与 JavaScript 的区别

  • WXS 有自己的数据类型

    • number : 数值
    • string :字符串
    • boolean:布尔值
    • object:对象
    • function:函数
    • array : 数组
    • date:日期
    • regexp:正则
  • WXS 不支持 ES6 及以上的语法形式

  • WXS 遵循 CommonJS 规范

    • module 对象
    • require() 函数
    • module.exports 对象

内嵌 WXS

1
2
3
4
5
6
7
<text>{{title.formatTitle(title)}}</text>

<wxs module="title">
module.exports.formatTitle = fucntion(title) {
return title.toUpperCase()
}
</wxs>

title.formatTitle(title) 的参数 title 是在页面 .js 文件中定义的 data 数据

外联 WXS

在小程序根目录下创建一个 utils 文件夹,在 utils 文件夹中创建一个 tools.wxs 文件

1
2
3
4
5
6
7
function formatTitle(title) {
return title.toUpperCase();
}

module.exports = {
formatTitle: formatTitle,
};

在 wxml 文件中引用 tools.wxs 文件

1
2
3
<text>{{title.formatTitle(title)}}</text>

<wxs src="../../utils/tools.wxs" module="title"></wxs>