将业务中的数据分离到单独的数据文件中
我们可以将一些公共的代码抽离成为一个单独的 js 文件,作为一个模块。模块只有通过 module.exports
或者 exports
才能对外暴露接口。
1 2 3 4 5 6 7 8 9 10 |
// common.js function sayHello(name) { console.log(`Hello ${name} !`) } function sayGoodbye(name) { console.log(`Goodbye ${name} !`) } module.exports.sayHello = sayHello exports.sayGoodbye = sayGoodbye |
使用require方法加载js模块儿文件
在需要使用这些模块的文件中,使用 require(path)
将公共代码引入
1 2 3 4 5 6 7 8 9 |
var common = require('common.js') Page({ helloMINA: function() { common.sayHello('MINA') }, goodbyeMINA: function() { common.sayGoodbye('MINA') } }) |
Template模板的使用
定义模板
使用name属性,作为模板的名字。然后在<template/>
内定义代码片段,如:
1 2 3 4 5 6 7 8 9 10 11 |
<!-- index: int msg: string time: string --> <template name="msgItem"> <view> <text> {{index}}: {{msg}} </text> <text> Time: {{time}} </text> </view> </template> |
使用模板
使用 is 属性,声明需要的使用的模板,然后将模板所需要的 data 传入,如:
1 |
<template is="msgItem" data="{{...item}}"/> |
1 2 3 4 5 6 7 8 9 |
Page({ data: { item: { index: 0, msg: 'this is a template', time: '2016-09-15' } } }) |
is 属性可以使用 Mustache 语法,来动态决定具体需要渲染哪个模板:
1 2 3 4 5 6 7 8 9 10 |
<template name="odd"> <view> odd </view> </template> <template name="even"> <view> even </view> </template> <block wx:for="{{[1, 2, 3, 4, 5]}}"> <template is="{{item % 2 == 0 ? 'even' : 'odd'}}"/> </block> |
模板的作用域
模板拥有自己的作用域,只能使用data传入的数据。
加载Template(wxml)
1 |
<import src="post-item/post-item-template.wxml" /> |
加载Template(wxss)
1 |
@import "post-item/post-item-template.wxss"; |