柚子快報(bào)邀請(qǐng)碼778899分享:小程序框架接口-getApp
柚子快報(bào)邀請(qǐng)碼778899分享:小程序框架接口-getApp
框架接口-getApp
getApp() 用于獲取小程序全局唯一的 App 實(shí)例,通過(guò)小程序應(yīng)用實(shí)例可實(shí)現(xiàn)數(shù)據(jù)或方法的共享
? 注意事項(xiàng):
1.不要在 App() 方法中使用 getApp() ,使用 this 就可以拿到 app 實(shí)例通過(guò) getApp() 獲取實(shí)例之后,不要私自調(diào)用生命周期函數(shù)
落地代碼:
?? app.js
App({
// 全局共享的數(shù)據(jù)
globalData: {
token: ''
},
// 全局共享的方法
setToken (token) {
// 如果想獲取 token,可以使用 this 的方式進(jìn)行獲取
this.globalData.token = token
// 在 App() 方法中如果想獲取 App() 實(shí)例,可以通過(guò) this 的方式進(jìn)行獲取
// 不能通過(guò) getApp() 方法獲取
}
})
?? pages/index/index.js
// getApp() 方法用來(lái)獲取全局唯一的 App() 實(shí)例
const appInstance = getApp()
Page({
login () {
// 不要通過(guò) app 實(shí)例調(diào)用鉤子函數(shù)
console.log(appInstance)
appInstance.setToken('fghioiuytfghjkoiuytghjoiug')
}
})
小程序頁(yè)面間通信
如果一個(gè)頁(yè)面通過(guò) wx.navigateTo 打開(kāi)一個(gè)新頁(yè)面,這兩個(gè)頁(yè)面間將建立一條數(shù)據(jù)通道
在 wx.navigateTo 的 success 回調(diào)中通過(guò) EventChannel 對(duì)象發(fā)射事件 被打開(kāi)的頁(yè)面可以通過(guò) this.getOpenerEventChannel() 方法獲得一個(gè) EventChannel 對(duì)象,進(jìn)行監(jiān)聽(tīng)、發(fā)射事件 wx.navigateTo 方法中可以定義 events 配置項(xiàng)接收被打開(kāi)頁(yè)面發(fā)射的事件
這兩個(gè) EventChannel 對(duì)象間可以使用 emit 和 on 方法相互發(fā)送、監(jiān)聽(tīng)事件。
落地代碼:
頁(yè)面 .js 文件
Page({
// 點(diǎn)擊按鈕觸發(fā)的事件處理函數(shù)
handler () {
wx.navigateTo({
url: '/pages/list/list',
events: {
// key:被打開(kāi)頁(yè)面通過(guò) eventChannel 發(fā)射的事件
// value:回調(diào)函數(shù)
// 為事件添加一個(gè)監(jiān)聽(tīng)器,獲取到被打開(kāi)頁(yè)面?zhèn)鬟f給當(dāng)前頁(yè)面的數(shù)據(jù)
currentevent: (res) => {
console.log(res)
}
},
success (res) {
// console.log(res)
// 通過(guò) success 回調(diào)函數(shù)的形參,可以獲取 eventChannel 對(duì)象
// eventChannel 對(duì)象給提供了 emit 方法,可以發(fā)射事件,同時(shí)攜帶參數(shù)
res.eventChannel.emit('myevent', { name: 'tom' })
}
})
}
})
被頁(yè)面 .js 文件
Page({
onLoad () {
// 通過(guò) this.getOpenerEventChannel() 可以獲取 EventChannel 對(duì)象
const EventChannel = this.getOpenerEventChannel()
// 通過(guò) EventChannel 提供的 on 方法監(jiān)聽(tīng)頁(yè)面發(fā)射的自定義事件
EventChannel.on('myevent', (res) => {
console.log(res)
})
// 通過(guò) EventChannel 提供的 emit 方法也可以向上一級(jí)頁(yè)面?zhèn)鬟f數(shù)據(jù)
// 需要使用 emit 定義自定義事件,攜帶需要傳遞的數(shù)據(jù)
EventChannel.emit('currentevent', { age: 10 })
}
})
自定義導(dǎo)航欄
小程序默認(rèn)的導(dǎo)航欄與 APP 一樣都位于頂部固定位置。但是默認(rèn)導(dǎo)航欄可能會(huì)影響小程序整體風(fēng)格,且無(wú)法滿足特定的設(shè)計(jì)需求,這時(shí)候,就需要進(jìn)行自定義導(dǎo)航欄。
在 app.json 或者 page.json 中,配置 navigationStyle 屬性為 custom,即可 自定義導(dǎo)航欄
在設(shè)置以后,就會(huì)移除默認(rèn)的導(dǎo)航欄,只保留右上角膠囊按鈕
落地代碼:
{
"usingComponents": {},
"navigationStyle": "custom"
}
/* pages/cate/cate.wxss */
.custom-swiper {
height: 440rpx;
}
.custom-swiper image {
height: 100%;
width: 100%;
}
柚子快報(bào)邀請(qǐng)碼778899分享:小程序框架接口-getApp
參考文章
本文內(nèi)容根據(jù)網(wǎng)絡(luò)資料整理,出于傳遞更多信息之目的,不代表金鑰匙跨境贊同其觀點(diǎn)和立場(chǎng)。
轉(zhuǎn)載請(qǐng)注明,如有侵權(quán),聯(lián)系刪除。