微信小程序使用函數的三種方法


一、使用來自不同頁面的函數

函數寫在util.js頁面

function formatTime(date) {
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()
 
  var hour = date.getHours()
  var minute = date.getMinutes()
  var second = date.getSeconds()
 
  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}
 
function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}
module.exports = {
  formatTime: formatTime,
}

使用函數
圖片描述
圖片描述

二、使用相同頁面的函數

get_productInformation: function () {
        。。。。
  },
getZones:function(){
        this.get_productInformation
  },

三、使用app.js內定義的函數

app.js代碼

//app.js
App({
  onLaunch: function() {
    //調用API從本地緩存中獲取數據
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)
  },
 get_a_test:function(){
    console.log('this is a test')
  },
  getUserInfo: function(cb) {
    var that = this
    if (this.globalData.userInfo) {
      typeof cb == "function" && cb(this.globalData.userInfo)
    } else {
      //調用登錄接口
      wx.getUserInfo({
        withCredentials: false,
        success: function(res) {
          that.globalData.userInfo = res.userInfo
          typeof cb == "function" && cb(that.globalData.userInfo)
        }
      })
    }
  },
 
  globalData: {
    userInfo: null,
    college_change:false
  }
})

在其他頁面中使用

圖片描述


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM