我們在開發微信小程序的時候,會用到自定義的函數功能,那么我們如何在小程序中寫這些JS,又如何在WXML中調用它們呢 ?換句話說在微信小程序{{}}中直接調用自定義的函數 ?
微信小程序的API:https://developers.weixin.qq.com/miniprogram/dev/reference/wxs/01wxs-module.html
一、創建公共的JS文件
本着代碼的規范化和項目的工程化,小程序中公共JS文件一般創建在utils目錄下,這樣,我們就可以在每個模塊頁面里調用它。比如:這里創建了一個公共文件:time.wxs(PS:微信小程序的公共文件一定要是wxs后綴),如圖所示:

二、編寫相關應用函數
打開time.wxs文件,然后在里面編寫函數:
1 /** 2 * 時間格式化:年月日是分秒 3 * @param {*} timestamp :時間戳13位 4 * @param {*} type:需要轉化后的時間格式 5 * eg. cn: 2020年02月02日 ; en:2020.02.02 6 */ 7 var timeFormat = { 8 timestampToTime: function (timestamp, type) { 9 if (timestamp && type === 'cn') { 10 let date = new Date(timestamp);//時間戳為10位需*1000,時間戳為13位的話不需乘1000 11 let Y = date.getFullYear() + '年'; 12 let M = (date.getMonth() + 1 < 10 ? (date.getMonth() + 1) : date.getMonth() + 1) + '月'; 13 let D = date.getDate() + '日'; 14 let h = date.getHours() < 10 ? '0' + (date.getHours()) + ':' : date.getHours() + ':'; 15 let m = date.getMinutes() < 10 ? '0' + (date.getMinutes()) : date.getMinutes(); 16 let s = date.getSeconds(); 17 18 return M + D + h + m; 19 } 20 if (timestamp && type === 'en') { 21 let date = new Date(timestamp);//時間戳為10位需*1000,時間戳為13位的話不需乘1000 22 let Y = date.getFullYear() + '.'; 23 let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '.'; 24 let D = date.getDate() + ''; 25 let h = date.getHours() < 10 ? '0' + (date.getHours()) + ':' : date.getHours() + ':'; 26 let m = date.getMinutes() < 10 ? '0' + (date.getMinutes()) : date.getMinutes(); 27 let s = date.getSeconds(); 28 29 return Y + M + D; 30 } 31 } 32 }; 33 34 35 // 導出對外暴露的屬性 36 module.exports = { 37 timestampToTime: timeFormat.timestampToTime 38 }
說明:
1、定義一個整體變量,以var開頭,
var 變量 = {};
2、編寫函數。函數格式為:
函數名:function(參數) {},具體參見上面的例子
3、通過module.exports引用函數,寫法如下:
module.exports = { 被使用的函數名:變量.具體函數 }
三、如何試用
1、在使用的頁面頭部引入文件,引入方式是:
1 <wxs module="time" src="../../utils/time.wxs"></wxs>
說明: module="文件名",我在utils文件夾里定義的文件名是time,所以這里的名稱與之對應
2、函數調用
1 <view class="msg">{{time.timestampToTime(item.endTime, "cn")}}已開獎</view>