在微信小程序wxml文件调用函数实现时间转换---使用wxs模块实现

1. 创建 WXS 模块文件(推荐单独存放)

在项目目录下新建 utils.wxs 文件,编写时间转换逻辑:

js 复制代码
// 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 文件中,通过 标签引入模块:

js 复制代码
<!-- 页面.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:

js 复制代码
<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 复制代码
// 页面.js
Page({
  data: {
    durationMs: 90000, // 毫秒
    durationSec: 150   // 秒
  }
})
html 复制代码
<!-- 页面.wxml -->
<text>动态毫秒值:{{timeUtils.convertToMinutes(durationMs)}}分钟</text>
<text>动态秒值:{{timeUtils.convertSecondsToMinutes(durationSec)}}分钟</text>
相关推荐
Geek_Vison12 小时前
2026 跨端框架横评:FinClip、Taro、uni-app、Remax、mPaaS 五款工具技术+业务双维度测评
小程序·uni-app·taro·mpaas·小程序容器
kidding72313 小时前
高效备忘清单工具类小程序
前端·计算机网络·微信小程序·小程序
黄华SJ520it14 小时前
二二复制公排模式小程序开发全解析
小程序
维双云16 小时前
商城小程序在线收款怎么做:收款链路、订单流转和后台处理怎么接
小程序
Geek_Vison16 小时前
APP集成了50多个小程序后,如何搭建一个小程序管理平台来管理这些小程序~
小程序·uni-app·apache·mpaas·小程序容器
万岳科技系统开发16 小时前
教育培训小程序搭建中的AI题库功能解析
人工智能·小程序
前端 贾公子16 小时前
小程序蓝牙打印探索与实践 (最终章)
前端·微信小程序·小程序
小羊Yveesss18 小时前
2026年个人能做微信小程序吗?
微信小程序·小程序
kidding72318 小时前
BMI 健康测量仪工具类小程序
前端·微信小程序·小程序
云迈科技-软件定制开发18 小时前
智慧物业小程序完整技术功能清单(业主端+管理后台+硬件联动|可直接落地)
小程序