小程序之-wxs

wxs

官方解释

  1. WXS 与 JavaScript 是不同的语言,有自己的语法,并不和 JavaScript 一致。
  2. WXS 的运行环境和其他 JavaScript 代码是隔离的,WXS 中不能调用其他 JavaScript 文件中定义的函数,也不能调用小程序提供的API。
  3. WXS 函数不能作为组件的事件回调。
  4. 由于运行环境的差异,在 iOS 设备上小程序内的 WXS 会比 JavaScript 代码快 2 ~ 20 倍。在 android 设备上二者运行效率无差异

使用方法


  1. wxs 代码可以写在wxml 文件中 的标签内, 或者 以 .wxs 为后缀名的文件内。(ps: 一般建议写在 .wxs 文件中

  2. 每个 .wxs 文件 或者 标签都是一个单独的模块, 当我们想在外部引入其中的私有变量或者函数时, 需要 module.exports 实现。

示例代码:

  1. 首先在tools.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";
  1. 然后在 wxml 页面中引用

{{tools.FOO}}
{{tools.bar(5)}}
{{tools.msg}}
  1. 页面中会显示
小程序之-wxs_第1张图片
result

注意事项


wxs 跟js 相比还是有很多限制的。

比如:

  • 不支持 es6 语法, 所以我们平常编码过程中使用的 解构, 箭头函数...都是不支持的。

  • 定义变量只能用 var 或者不写 代表全局。因为 let ,cons是 es6 的

  • 数据类型 wxs 语法是没有 **symbol null undefined **的。 其他的数据类型都支持。

    具体都有:

    • number : 数值
    • string :字符串
    • boolean:布尔值
    • object:对象
    • function:函数
    • array : 数组
    • date:日期
    • regexp:正则

判断wxs中的数据类型

我们知道 在 js 中判断数据类型可以用 typeof && Object.prototype.toString.call()

typeof undefined === 'undefined'   // true
typeof true      === 'bollean'    // true
typeof 25        === 'number'    // true
typeof 'shit'      === 'string' // true
typeof { name: 'mars'} === 'object'  // true

// 以及 es6中的Symbol 
typeof Symbol()  === 'symbol'    // true


typeof function a() {} === 'function'  // true

以上6种数据类型都有与之同名的字符串与之对应。 但是 mull是 不再其中 的

typeof null === 'object'    // true

我们知道当 遇到 Array Date Object... 时 typeof 都会识别为 object

此时需要 Object.prototype.toString.call()

小程序之-wxs_第2张图片
fuck

但是在wxs 中 有属性 constructor 会返回相应数据类型的字符串

如图:

小程序之-wxs_第3张图片
business

更多详细介绍戳

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