最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

【已解决】小程序中如何实现全局的工具或帮助函数

工具 crifan 710浏览 0评论
折腾:
【未解决】小程序中的js实现字符串的去除首尾空格
期间,想要把一些相对通用的函数,比如trim,放到全局的地方,比如util,helper之类,使得所有页面都能调用的到。
突然自己发现:
微信自带模板中,都有个util.js了:
然后看看别处如何调用
全局搜一下:
const formatTime = date => {
  const year = date.getFullYear()
...
  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
}
看到用法了:
//logs.js
const util = require('../../utils/util.js')

return util.formatTime(new Date(log))
自己去照葫芦画瓢试试
【总结】
最后用代码:
util/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
}

const trim = originStr => {
  var trimmedStr = originStr.replace(/(^\s*)|(\s*$)/g, "")
  console.log("trim: %s -> %s", originStr, trimmedStr)
  return trimmedStr
}

module.exports = {
  formatTime: formatTime,
  trim: trim,
}
其他地方调用:
pages/index/index.js
const util = require('../../utils/util.js')


    var trimmedInput = util.trim(this.data.curInputValue)
    console.log("trimmedInput=%s", trimmedInput)
是可以实现util全局函数的效果的,运行也没问题:

转载请注明:在路上 » 【已解决】小程序中如何实现全局的工具或帮助函数

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
80 queries in 0.176 seconds, using 22.08MB memory