WXS 代码可以编写在 wxml 文件中的 标签内,或以 .wxs 为后缀名的文件内
一,模块
- 每一个 .wxs 文件和 标签都是一个单独的模块。
- 每个模块都有自己独立的作用域。即在一个模块里面定义的变量与函数,默认为私有的,对其他模块不可见。
- 一个模块要想对外暴露其内部的私有变量与函数,只能通过 module.exports 实现。
二,wxs 文件
创建 .wxs 文件,在其中直接编写 WXS 脚本
var foo = "'hello world' from comm.wxs";
var bar = function(d) {
return d;
}
module.exports = {
foo: foo,
bar: bar
};
三,module 对象
每个 wxs 模块均有一个内置的 module 对象
exports: 通过该属性,可以对外共享本模块的私有变量与函数
var foo = "'hello world' from tools.wxs";
var bar = function (d) {
return d;
}
module.exports = {
FOO: foo,
bar: bar,
};
module.exports.msg = "some msg";
<wxs src="./../tools.wxs" module="tools" />
<view> {{tools.msg}} </view>
<view> {{tools.bar(tools.FOO)}} </view>
四,require函数
wxs模块中引用其他 wxs 文件模块,可以使用 require 函数
- 只能引用 .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" />
标签
属性名 | 类型 | 说明 |
---|---|---|
src | String | 只能引用 .wxs 文件模块,且必须使用相对路径。。 |
module | String | 当前 标签的模块名。必填字段 |