框架接口-getApp
getApp()
用于獲取小程序全局唯一的 App
實例,通過小程序應用實例可實現數據或方法的共享
📌 注意事項:
- 1.不要在 App() 方法中使用 getApp() ,使用 this 就可以拿到 app 實例
- 通過
getApp()
獲取實例之后,不要私自調用生命周期函數
落地代碼:
?? app.js
App({// 全局共享的數據globalData: {token: ''},// 全局共享的方法setToken (token) {// 如果想獲取 token,可以使用 this 的方式進行獲取this.globalData.token = token// 在 App() 方法中如果想獲取 App() 實例,可以通過 this 的方式進行獲取// 不能通過 getApp() 方法獲取}})
?? pages/index/index.js
// getApp() 方法用來獲取全局唯一的 App() 實例
const appInstance = getApp()Page({login () {// 不要通過 app 實例調用鉤子函數console.log(appInstance)appInstance.setToken('fghioiuytfghjkoiuytghjoiug')}})
小程序頁面間通信
如果一個頁面通過 wx.navigateTo
打開一個新頁面,這兩個頁面間將建立一條數據通道
-
在
wx.navigateTo
的success
回調中通過EventChannel
對象發射事件 -
被打開的頁面可以通過
this.getOpenerEventChannel()
方法獲得一個EventChannel
對象,進行監聽、發射事件 -
wx.navigateTo
方法中可以定義events
配置項接收被打開頁面發射的事件
這兩個 EventChannel
對象間可以使用 emit
和 on
方法相互發送、監聽事件。
落地代碼:
頁面 .js 文件
Page({// 點擊按鈕觸發的事件處理函數handler () {wx.navigateTo({url: '/pages/list/list',events: {// key:被打開頁面通過 eventChannel 發射的事件// value:回調函數// 為事件添加一個監聽器,獲取到被打開頁面傳遞給當前頁面的數據currentevent: (res) => {console.log(res)}},success (res) {// console.log(res)// 通過 success 回調函數的形參,可以獲取 eventChannel 對象// eventChannel 對象給提供了 emit 方法,可以發射事件,同時攜帶參數res.eventChannel.emit('myevent', { name: 'tom' })}})}})
被頁面 .js 文件
Page({onLoad () {// 通過 this.getOpenerEventChannel() 可以獲取 EventChannel 對象const EventChannel = this.getOpenerEventChannel()// 通過 EventChannel 提供的 on 方法監聽頁面發射的自定義事件EventChannel.on('myevent', (res) => {console.log(res)})// 通過 EventChannel 提供的 emit 方法也可以向上一級頁面傳遞數據// 需要使用 emit 定義自定義事件,攜帶需要傳遞的數據EventChannel.emit('currentevent', { age: 10 })}})
自定義導航欄
小程序默認的導航欄與 APP 一樣都位于頂部固定位置。但是默認導航欄可能會影響小程序整體風格,且無法滿足特定的設計需求,這時候,就需要進行自定義導航欄。
在 app.json 或者 page.json 中,配置 navigationStyle 屬性為 custom,即可 自定義導航欄
在設置以后,就會移除默認的導航欄,只保留右上角膠囊按鈕
落地代碼:
{"usingComponents": {},"navigationStyle": "custom"
}
<!--pages/cate/cate.wxml-->
<!-- <text>pages/cate/cate.wxml</text> --><swiper class="custom-swiper" indicator-dots autoplay interval="2000"><swiper-item><image src="../../assets/banner/banner-1.png" mode=""/></swiper-item><swiper-item><image src="../../assets/banner/banner-2.png" mode=""/></swiper-item><swiper-item><image src="../../assets/banner/banner-3.png" mode=""/></swiper-item>
</swiper>
/* pages/cate/cate.wxss */.custom-swiper {height: 440rpx;
}.custom-swiper image {height: 100%;width: 100%;
}