11 WXS-模块

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

一,模块

  1. 每一个 .wxs 文件和 标签都是一个单独的模块。
  2. 每个模块都有自己独立的作用域。即在一个模块里面定义的变量与函数,默认为私有的,对其他模块不可见。
  3. 一个模块要想对外暴露其内部的私有变量与函数,只能通过 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 函数

  1. 只能引用 .wxs 文件模块,且必须使用相对路径
  2. wxs 模块均为单例wxs 模块在第一次被引用时,会自动初始化为单例对象。
  3. 如果一个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" />

标签

属性名类型说明
srcString只能引用 .wxs 文件模块,且必须使用相对路径。。
moduleString当前 标签的模块名。必填字段
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值