微信小程序使用函数的三种方法

我就是我 2022-12-31 01:29 106阅读 0赞

使用来自不同页面的函数

函数写在util.js页面

  1. function formatTime(date) {
  2. var year = date.getFullYear()
  3. var month = date.getMonth() + 1
  4. var day = date.getDate()
  5. var hour = date.getHours()
  6. var minute = date.getMinutes()
  7. var second = date.getSeconds()
  8. return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
  9. }
  10. function formatNumber(n) {
  11. n = n.toString()
  12. return n[1] ? n : '0' + n
  13. }
  14. module.exports = {
  15. formatTime: formatTime,
  16. }

使用函数
图片描述
图片描述
使用相同页面的函数

  1. get_productInformation: function () {
  2. 。。。。
  3. },
  4. getZones:function(){
  5. this.get_productInformation
  6. },

使用app.js内定义的函数

app.js代码

  1. //app.js
  2. App({
  3. onLaunch: function() {
  4. //调用API从本地缓存中获取数据
  5. var logs = wx.getStorageSync('logs') || []
  6. logs.unshift(Date.now())
  7. wx.setStorageSync('logs', logs)
  8. },
  9. get_a_test:function(){
  10. console.log('this is a test')
  11. },
  12. getUserInfo: function(cb) {
  13. var that = this
  14. if (this.globalData.userInfo) {
  15. typeof cb == "function" && cb(this.globalData.userInfo)
  16. } else {
  17. //调用登录接口
  18. wx.getUserInfo({
  19. withCredentials: false,
  20. success: function(res) {
  21. that.globalData.userInfo = res.userInfo
  22. typeof cb == "function" && cb(that.globalData.userInfo)
  23. }
  24. })
  25. }
  26. },
  27. globalData: {
  28. userInfo: null,
  29. college_change:false
  30. }
  31. })

在其他页面中使用
在这里插入图片描述

发表评论

表情:
评论列表 (有 0 条评论,106人围观)

还没有评论,来说两句吧...

相关阅读