小程序之脚本语言

WXS(WeiXin Script)

与 javascript 是不同的语言,有自己的语法,并不和 javascript 一致。

运行环境和其他 javascript 代码是隔离的,wxs中不能调用其他 javascript 文件中定义的函数,也 不能调用 小程序提供的API。
wxs 函数不能作为组件的事件回调


页面渲染
"m1" > var msg = "hello world";module.exports.message = msg; {{m1.message}}
页面输出:
hello world




数据处理
// page.js Page({ data: { array: [ 1 , 2 , 3 , 4 , 5 , 1 , 2 , 3 , 4 ] }})
"m1" > var getMax = function(array) { var max = undefined; for (var i = 0; i < array.length; ++i) { max = max = == undefined ? array[i] : (max > = array[i] ? max : array[i]); } return max;}module.exports.getMax = getMax; {{m1.getMax(array)}}
页面输出:
5

WXS 模块
可以编写在 wxml 文件中的   标签内,或以  .wxs  为后缀名的文件内。
每一个  .wxs  文件和   标签都是一个单独的模块。
在一个模块里面定义的变量与函数,默认为私有的,对其他模块不可见。
一个模块要想对外暴露其内部的私有变量与函数, 只能 通过  module.exports  实现。




// /pages/comm.wxs var foo = "'hello world' from comm.wxs" ; var bar = function ( d ) { return d;} module .exports = { foo: foo, bar: bar};


每个  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" ;
"./../tools.wxs" module= " tools " /> {{tools.msg}} {{tools.bar(tools.FOO)}}
页面输出:
some msg'hello world' from tools.wxs

  .wxs  文件可以被其他的  .wxs  文件 或 WXML 中的   标签引用。
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);
"./../logic.wxs" module= "logic" />
控制台输出:
'hello world' from tools.wxslogic.wxssome msg


 标签

属性名 说明
module 当前 标签的模块名。必填字段。
src 引用 .wxs 文件的相对路径。
仅当本标签为单闭合标签或标签的内容为空时有效。
其中:
module 属性是当前   标签的模块名。在单个 wxml 文件内, 建议其值唯一 。有重复模块名则按照先后顺序 覆盖 (后者覆盖前者)。不同文件之间的 wxs 模块名 不会相互覆盖。


"foo" > var some_msg = "hello world";module.exports = { msg : some_msg,} {{foo.msg}}
页面输出:
hello world
上面例子声明了一个名字为  foo  的模块,将  some_msg  变量暴露出来,供当前页面使用。

src 属性可以用来引用其他的  wxs  文件模块。
引用的时候,要注意如下几点:
  • 只能引用 .wxs 文件模块,且必须使用相对路径。
  • wxs 模块均为单例,wxs 模块在第一次被引用时,会自动初始化为单例对象。多个页面,多个地方,多次引用,使用的都是同一个 wxs 模块对象。


// /pages/index/index.js Page({ data: { msg: "'hello wrold' from js" , }})

"./../comm.wxs" module= "some_comms" > {{some_comms.bar(some_comms.foo)}} {{some_comms.bar(msg)}}
页面输出:
'hello world' from comm.wxs'hello wrold' from js

注意
  •  模块只能在定义模块的 WXML 文件中被访问到。使用  或  时, 模块不会被引入到对应的 WXML 文件中。