微信小程序视图层WXS_小程序WXS模块

时间:2018-12-06 20:40:28   收藏:0   阅读:196

微信小程序视图层WXS_小程序WXS模块

微信小程序的WXS 代码可以编写在 小程序wxml 文件中的 <wxs> 标签内,或以 .wxs 为后缀名的文件内。

模块

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

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

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

.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 对象。

属性

示例代码:

// /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 函数。

引用的时候,要注意如下几点:

示例代码:

// /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

<wxs> 标签

属性名类型默认值说明
module String   当前 <wxs> 标签的模块名。必填字段。
src String   引用 .wxs 文件的相对路径。仅当本标签为单闭合标签或标签的内容为空时有效。

module 属性

module 属性是当前 <wxs> 标签的模块名。在单个微信小程序的 wxml 文件内,建议其值唯一。有重复模块名则按照先后顺序覆盖(后者覆盖前者)。不同文件之间的 wxs 模块名不会相互覆盖。

module 属性值的命名必须符合下面两个规则:

示例代码:

<!--wxml-->

<wxs module="foo">
var some_msg = "hello world";
module.exports = {
    msg : some_msg,
}
</wxs>
<view> {{foo.msg}} </view>

页面输出:

hello world

上面例子声明了一个名字为 foo 的模块,将 some_msg 变量暴露出来,供当前页面使用。

src 属性

src 属性可以用来引用其他的 wxs 文件模块。

引用的时候,要注意如下几点:

示例代码:

// /pages/index/index.js

Page({
  data: {
    msg: "‘hello wrold‘ from js",
  }
})
<!-- /pages/index/index.wxml -->

<wxs src="./../comm.wxs" module="some_comms"></wxs>
<!-- 也可以直接使用单标签闭合的写法
<wxs src="./../comm.wxs" module="some_comms" />
-->

<!-- 调用 some_comms 模块里面的 bar 函数,且参数为 some_comms 模块里面的 foo -->
<view> {{some_comms.bar(some_comms.foo)}} </view>
<!-- 调用 some_comms 模块里面的 bar 函数,且参数为 page/index/index.js 里面的 msg -->
<view> {{some_comms.bar(msg)}} </view>

页面输出:

‘hello world‘ from comm.wxs
‘hello wrold‘ from js

上述例子在文件 /page/index/index.wxml 中通过 <wxs> 标签引用了 /page/comm.wxs 模块。

注意

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!