模块化也就是将一些通用的东西抽出来放到一个文件中,通过module.exports去暴露接口。我们在最初新建项目时就有个util.js文件就是被模块化处理时间的
/** * 处理具体业务逻辑 */ function formatTime(date) { //获取年月日 var year = date.getFullYear() var month = date.getMonth() + 1 var day = date.getDate() //获取时分秒 var hour = date.getHours() var minute = date.getMinutes() var second = date.getSeconds(); //格式化日期 return [year, month, day].map(formatNumber).join(‘/‘) + ‘ ‘ + [hour, minute, second].map(formatNumber).join(‘:‘) } function formatNumber(n) { n = n.toString() return n[1] ? n : ‘0‘ + n } /** * 模块化导出暴露接口 */ module.exports = { formatTime: formatTime }
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
使用方式:

//导入模块化方式 var util = require(‘../../utils/util.js‘) Page({ data: { logs: [] }, onLoad: function () { this.setData({ logs: (wx.getStorageSync(‘logs‘) || []).map(function (log) { // 通过暴露的接口调用模块化方法 return util.formatTime(new Date(log)) }) }) } })