微信小程序使用函数的三种方法
--使用來(lái)自不同頁(yè)面的函數(shù)
函數(shù)寫(xiě)在util.js頁(yè)面
function formatTime(date) {var year = date.getFullYear()var month = date.getMonth() + 1var 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, }使用函數(shù)
?
使用相同頁(yè)面的函數(shù)
get_productInformation: function () {。。。。}, getZones:function(){this.get_productInformation},使用app.js內(nèi)定義的函數(shù)
app.js代碼
//app.js App({onLaunch: function() {//調(diào)用API從本地緩存中獲取數(shù)據(jù)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 = thisif (this.globalData.userInfo) {typeof cb == "function" && cb(this.globalData.userInfo)} else {//調(diào)用登錄接口wx.getUserInfo({withCredentials: false,success: function(res) {that.globalData.userInfo = res.userInfotypeof cb == "function" && cb(that.globalData.userInfo)}})}},globalData: {userInfo: null,college_change:false} })在其他頁(yè)面中使用
---------------------------------------------------------------------------------------------------------------------------------
App()含義:
注冊(cè)一個(gè)小程序
小程序的入口方法
例如:
app.js
App({
? onLaunch: function(options) {
? ? console.log("onLaunch");
? },
? onShow: function(options) {
? ? ? console.log("onShow");
? ? ? // Do something when show.
? },
? onHide: function() {
? ? ? console.log("onHide");
? ? ? // Do something when hide.
? },
? onError: function(msg) {
? ? ? console.log(msg)
? },
? test:function() {
? ? console.log("I am func from App.js");
? },
? globalData: {
? ? userInfo:null,
? ? helloFromApp:'Hello,I am From App.js'
? }
})
在其他子頁(yè)面如何使用呢?
demo.js
var app = getApp();
console.log(app.globalData.helloFromApp); // 調(diào)用全局變量
app.test(); // 調(diào)用全局方法
我們發(fā)現(xiàn),全局變量和全局方法都被調(diào)用了。
通過(guò)getApp獲取全局對(duì)象,然后進(jìn)行全局變量和全局方法的使用。
注意:
App() 必須在 app.js 中注冊(cè),且不能注冊(cè)多個(gè)。
不要在定義于 App() 內(nèi)的函數(shù)中調(diào)用 getApp() ,使用 this 就可以拿到 app 實(shí)例。
this.globalData.userInfo = res.userInfo
1.
不要在 onLaunch 的時(shí)候調(diào)用 getCurrentPages(),此時(shí) page 還沒(méi)有生成。
?
總結(jié)
以上是生活随笔為你收集整理的微信小程序使用函数的三种方法的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 计算机毕业设计JAVA电影推荐网站myb
- 下一篇: 使用链表进行奇偶分排 c语言