1. 創建 WXS 模塊文件(推薦單獨存放)
在項目目錄下新建 utils.wxs 文件,編寫時間轉換邏輯:
// utils.wxs
module.exports = {// 將毫秒轉換為分鐘(保留1位小數)convertToMinutes: function(ms) {if (typeof ms !== 'number') return '0.0'return (Math.round(ms / 60000 * 10) / 10).toFixed(1)},// 將秒轉換為分鐘(保留1位小數)convertSecondsToMinutes: function(seconds) {if (typeof seconds !== 'number') return '0.0'return (Math.round(seconds / 60 * 10) / 10).toFixed(1)}
}
2. 在 WXML 中引入 WXS 模塊
在需要使用的 WXML 文件中,通過 標簽引入模塊:
<!-- 頁面.wxml -->
<wxs src="../../utils.wxs" module="timeUtils" /><!-- 示例:顯示轉換結果 -->
<view><!-- 轉換毫秒(如 90000ms = 1.5分鐘) --><text>90000ms = {{timeUtils.convertToMinutes(90000)}}分鐘</text><!-- 轉換秒(如 150秒 = 2.5分鐘) --><text>150秒 = {{timeUtils.convertSecondsToMinutes(150)}}分鐘</text>
</view>
3. 直接內聯 WXS 代碼(可選)
如果不想單獨創建文件,也可以直接在 WXML 中內聯 WXS:
<wxs module="timeUtils">module.exports = {convertToMinutes: function(ms) {if (typeof ms !== 'number') return '0.0'return (Math.round(ms / 60000 * 10) / 10).toFixed(1)}}
</wxs><!-- 調用方式相同 -->
<text>{{timeUtils.convertToMinutes(120000)}}</text>
4. 動態數據綁定(結合 JS)
如果需要轉換動態數據,在 Page 的 JS 中定義數據,通過 {{}} 綁定:
// 頁面.js
Page({data: {durationMs: 90000, // 毫秒durationSec: 150 // 秒}
})
<!-- 頁面.wxml -->
<text>動態毫秒值:{{timeUtils.convertToMinutes(durationMs)}}分鐘</text>
<text>動態秒值:{{timeUtils.convertSecondsToMinutes(durationSec)}}分鐘</text>