微信小程序 —— 模块化方法的总结
2017-12-06 22:24
323 查看
一、. JS 文件
可以将一些公共的代码抽离成为一个单独的 js 文件,作为一个模块。模块只有通过 module.exports 才能对外暴露接口。function sayHello(name) { console.log(`Hello ${name} !`) } function sayGoodbye(name) { console.log(`Goodbye ${name} !`) } module.exports.sayHello = sayHello
其他文件调用模块 .js文件(使用 require(path) )
var common = require('common.js') Page({ helloMINA: function() { common.sayHello('MINA') }, })
二、WXS 模块
1、< wxs > 标签
属性:module —— 当前 < wxs> 标签的模块名。必填字段。
src —— 引用 .wxs 文件的相对路径。
< wxs > 标签模块的定义和使用
<wxs module="foo"> var some_msg = "hello world"; module.exports = { msg : some_msg, } </wxs> <view> {{foo.msg}} </view>
2、. wxs文件
. 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文件(使用 require(path) )
var tools = require("./tools.wxs"); console.log(tools.FOO); console.log(tools.bar("logic.wxs")); console.log(tools.msg);
< wxs > 标签调用模块 .wxs文件(调用 .js文件和 .wxs文件的不同点)
<wxs src="./../logic.wxs" module="tool" />
三、template
a、WXML提供模板(template),可以在模板中定义代码片段,然后在不同的地方调用。b、模板拥有自己的作用域,只能使用 data 传入的数据以及模板定义文件中定义的 < wxs /> 模块。
1、定义模板 template
使用 name 属性,作为模板的名字。然后在内定义代码片段,如:<!-- first.wxml --> <template name="msgItem"> <view> <text> {{index}}: {{msg}} </text> <text> Time: {{time}} </text> </view> </template>
2、当前文件调用模板 template
使用 is 属性,声明需要的使用的模板,然后将模板所需要的 data 传入,如:(1)传入单个data
<!-- first.wxml --> <template is="msgItem" data="{{text: 'forbar'}}"/>
(2)传入多个data
<!-- first.wxml --> <template is="msgItem" data="{{...item}}"/>
<!-- first.js --> Page({ data: { item: { index: 0, msg: 'this is a template', time: '2016-09-15' } } })
3、其他文件调用模板 template(使用 import)
传入单个data,若要传入多个data可仿照上一段代码<!-- second.wxml --> <import src="first.wxml"/> <template is="msgItem" data="{{text: 'forbar'}}"/>
4、其他文件将除了 < template/> < wxs/> 外的整个代码引入(使用include)
<!-- second.wxml --> <include src="header.wxml"/> <view> body </view> <include src="footer.wxml"/>
<!-- header.wxml --> <view> header </view>
<!-- footer.wxml --> <view> footer </view>
参考链接:
https://mp.weixin.qq.com/debug/wxadoc/dev/
相关文章推荐
- 微信小程序 传值取值的几种方法总结
- 微信小程序 传值取值的几种方法总结,百分百会用到
- 微信小程序 传值取值的几种方法总结
- 微信小程序 传值取值的几种方法总结
- 微信小程序 跳转页面的两种方法详解
- 微信小程序开发总结
- 原创经验:微信小程序开发总结
- 微信门店小程序怎样创建 门店小程序创建方法简介
- 微信小程序下拉刷新上拉加载的两种实现方法
- 微信小程序 按钮滑动的实现方法
- 微信小程序适配iphoneX的实现方法
- 微信小程序获取手机网络状态的方法【附源码下载】
- 微信小程序(微信应用号)开发ide安装解决方法
- 如何高效编写微信小程序呢?来看看腾讯工程师这个方法
- 微信小程序中一些有用的组件总结
- 在微信小程序中渲染HTML内容的方法示例
- 微信小程序 教程之模块化
- 总结:微信小程序入口大全
- 微信小程序-IOS时间戳坑解决方法
- 微信开放平台之公众号小程序第三方平台探讨总结