WXS 代码可以编写在 wxml 文件中的 <wxs>
标签内,或以 .wxs
为后缀名的文件内。
在微信开发者工具里面,右键可以直接创建 .wxs
文件,在其中直接编写 WXS 脚本。
示例代码:
// /pages/comm.wxs
var foo = "'hello world' from comm.wxs";
var bar = function(d) {
return d;
}
module.exports = {
foo: foo,
bar: bar
};
上述例子在 /pages/comm.wxs
的文件里面编写了 WXS 代码。该 .wxs
文件可以被其他的 .wxs
文件 或 WXML 中的 <wxs>
标签引用。
# module 对象
每个 wxs
模块均有一个内置的 module
对象。
# 属性
exports
: 通过该属性,可以对外共享本模块的私有变量与函数。
示例代码:
在开发者工具中预览效果
// /pages/tools.wxs
var foo = "'hello world' from tools.wxs";
var bar = function (d) {
return d;
}
module.exports = {
FOO: foo,
bar: bar,
};
module.exports.msg = "some msg";
<!-- page/index/index.wxml -->
<wxs src="./../tools.wxs" module="tools" />
<view> {{tools.msg}} </view>
<view> {{tools.bar(tools.FOO)}} </view>
页面输出:
some msg
'hello world' from tools.wxs
# require函数
在.wxs
模块中引用其他 wxs
文件模块,可以使用 require
函数。
引用的时候,要注意如下几点:
- 只能引用
.wxs
文件模块,且必须使用相对路径。 wxs
模块均为单例,wxs
模块在第一次被引用时,会自动初始化为单例对象。多个页面,多个地方,多次引用,使用的都是同一个wxs
模块对象。- 如果一个
wxs
模块在定义之后,一直没有被引用,则该模块不会被解析与运行。
示例代码:
在开发者工具中预览效果
// /pages/tools.wxs
var foo = "'hello world' from tools.wxs";
var bar = function (d) {
return d;
}
module.exports = {
FOO: foo,
bar: bar,
};
module.exports.msg = "some msg";
// /pages/logic.wxs
var tools = require("./tools.wxs");
console.log(tools.FOO);
console.log(tools.bar("logic.wxs"));
console.log(tools.msg);
<!-- /page/index/index.wxml -->
<wxs src="./../logic.wxs" module="logic" />
控制台输出:
'hello world' from tools.wxs
logic.wxs
some msg