WXS语法介绍


 

WXS(WeiXin Script)是小程序的一套脚本语言,结合 WXML,可以构建出页面的结构。

 

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

 

模块

WXS 代码可以编写在 wxml 文件中的 标签内,或以 .wxs 为后缀名的文件内。

 

每一个 .wxs 文件和 <wxs> 标签都是一个单独的模块。

每个模块都有自己独立的作用域。即在一个模块里面定义的变量与函数,默认为私有的,对其他模块不可见。

一个模块要想对外暴露其内部的私有变量与函数,只能通过 module.exports 实现。

  .wxs 文件
  在微信开发者工具里面,右键可以直接创建 .wxs 文件,在其中直接编写 WXS 脚本。

 

 1 // /pages/tools.wxs
 2 
 3 var foo = "'hello world' from tools.wxs"
 4 var bar = function (d) {
 5   return d
 6 }
 7 module.exports = {
 8   FOO: foo,
 9   bar: bar,
10 }
11 module.exports.msg = "some msg"
12 
13 
14 
15 <!-- /page/index.wxml -->
16 
17 <wxs src="./tools.wxs" module="tools" />
18 <view> {{tools.msg}} </view>
19 <view> {{tools.bar(tools.FOO)}} </view>
20 
21 
22 
23 // 页面输出
24 
25 some msg
26 'hello world' from tools.wxs
1 <!--wxml-->
2 
3 <wxs module="foo">
4 var some_msg = "hello world";
5 module.exports = {
6   msg : some_msg,
7 }
8 </wxs>
9 <view> {{foo.msg}} </view>

 

标签

<wxs> 标签

 

require函数

.wxs模块中引用其他 wxs 文件模块,可以使用 require 函数。

 1 // /pages/tools.wxs
 2 
 3 var foo = "'hello world' from tools.wxs"
 4 var bar = function (d) {
 5   return d
 6 }
 7 module.exports = {
 8   FOO: foo,
 9   bar: bar,
10 }
11 module.exports.msg = "some msg"
12 
13 
14 
15 // /pages/logic.wxs
16 
17 var tools = require("./tools.wxs")
18 
19 console.log(tools.FOO)
20 console.log(tools.bar("logic.wxs"))
21 console.log(tools.msg)
22 
23 
24 
25 <!-- /page/index/index.wxml -->
26 
27 <wxs src="./../logic.wxs" module="logic" />
28 
29 
30 
31 控制台输出:
32 
33 'hello world' from tools.wxs
34 logic.wxs
35 some msg

 

注意

  • <wxs> 模块只能在定义模块的 WXML 文件中被访问到。使用 <include> 或 <import> 时,<wxs> 模块不会被引入到对应的 WXML 文件中。
  • <template> 标签中,只能使用定义该 <template> 的 WXML 文件中定义的 <wxs> 模块。
  • wxs 语法不支持es6的写法
posted @ 2021-02-25 11:15  地yu荒冢  阅读(474)  评论(0编辑  收藏  举报