index/index.wxml
<!--index.wxml-->
<view class="container">
<!-- 建立按鈕,爲按鈕綁定函數 -->
<button bindtap="getTime">點擊獲取當前時間</button>
<!-- wx:if判斷是否存在 -->
<text wx:if="{{time}}">{{time}}</text>
</view>
index/index.js
//index.js
var util = require('../../utils/util.js');
Page({
data: {
},
//給按鈕綁定getTime事件
getTime:function(){
var time = util.formatTime(new Date())
//爲頁面中time賦值
this.setData({
time:time
})
//打印
console.log(time)
}
})
utils/util.js
// utils/util.js
const formatTime = date => {
const year = date.getFullYear()
const month = date.getMonth() + 1
const day = date.getDate()
const hour = date.getHours()
const minute = date.getMinutes()
const second = date.getSeconds()
return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}
const formatNumber = n => {
n = n.toString()
return n[1] ? n : '0' + n
}
module.exports = {
formatTime: formatTime
}
注意點:1.通過bindtap爲按鈕綁定函數。
2.wx:if 判斷 {{time}} 值是否爲空,空則不顯示。
3.調用util.js中的formatTime完成時間對象的創建與賦值。
4.setData方法爲頁面中 {{time}} 賦值。
整體結構: