小程序應用生命周期
我們知道小程序有應用生命周期和頁面生命周期
在App.vue中可以監聽應用生命周期:
- onLaunch
- onShow
- onHide
- onError
- onUniNViewMessage
頁面生命周期
- onLoad
- onShow
- onReady
- onHide
- onUnload
- ...
而這其中有幾種情況需要注意
1.小程序從前台進入后台,再從后台進入前台生命周期變化
- 頁面onHide
- 小程序onHide
- 小程序onShow
- 頁面onShow
2.結合vue生命周期,一個非tabbar頁面的具體周期先后順序如下
- beforeCreate
- created
- beforeMount
- onLoad
- onShow
- mounted
- onReady
- beforeUpdate
- updated
- onUnload
- beforeDestroy
- destoryed
3.父子組件生命周期
- 父beforeCreate
- 父created
- 父beforeMount
- 子beforeCreate
- 子created
- 子beforeMount
- 父onLoad
- 父onShow
- 子mounted
- 父mounted
- 父onReady
4.tabbar頁面
一般情況下tabbar頁面不會經歷onUnload和beforeDestroy和destroyed,可以理解為tabbar頁面是緩存模式,在tabbar頁面的互相切換中,上一個tabbar頁面出棧,下一個進棧
5.onLoad獲取頁面傳遞參數
onLoad(o) { console.log(o) this.type = Number.parseInt(o.type); }
6.mounted和onReady修改data會觸發beforeUpdate和updated生命周期
7.beforeDestroy時還能獲取vue實例
8.onPullDownRefresh()
下拉刷新,需要在頁面的配置文件中配上
{ "path": "pages/device/deviceList/deviceList", "style": { "navigationBarTitleText": "設備管理", "enablePullDownRefresh": true, "backgroundTextStyle": "dark" } },
完成刷新后要關閉刷新狀態uniapp下用uni.stopPullDownRefresh()
9.onReachBottom()
觸底加載,基本是列表頁面觸底加載下一頁
頁面棧
用getCurrentPages()獲取
let pages = getCurrentPages() console.log(pages) console.log(pages[pages.length-1]) //拿到上一頁
因此息息相關的就是頁面跳轉方法
uni.redirectTo()關閉當前頁面,跳轉到應用內的某個頁面。當前頁出棧
uni.reLaunch()關閉所有頁面,打開到應用內的某個頁面。
uni.switchTab()跳轉到 tabBar 頁面,並關閉其他所有非 tabBar 頁面。
列表頁面
有四種情況:
1.初始化加載頁面,只用page,size請求
2.下拉刷新list(可能帶查詢條件)或者查詢條件下搜索list
// 下拉刷新 onPullDownRefresh() { this.param.page = 1 this.getList(2) },
methods: {
// 初始化請求參數
initParam(){
this.param.page = { page:1,size:20 }
},
// 搜索 search() { this.initParam() let obj = { ...this.searchParam} Object.assign(this.param, obj) //查詢條件拼接 this.getList(1) }, }
3.觸底加載下一頁數組list等於之前的list拼接請求接口拿到的下一頁數據
// 觸底加載下一頁 onReachBottom() { if (!this.pagMsg.last) { this.param.page++ this.getList(3) } },
4.在list頁面對某一項進行刪除,重新渲染已經拿到的數組內容。業務場景為觸底刷新了4次,即你在第4頁了,此時刪除列表中的一個item,數組要做相應的更新而你還在第4頁;或者你改變了第四頁列表中item的一個字段,要做相應更新。此時直接拿四頁的列表。
// 不能直接改param
let param = { ...this.param} param.size *= param.page param.page = 1 this.getList(4, param)
getList()方法
// 獲取列表,type填1為正常初始化加載頁面;type填2為下拉加載,加載成功要停止當前頁面下拉刷新;type填3為觸底加載下一頁數組拼接,type填4時為處理時使用,有第二個參數 getList(type, obj) { this.more = 'loading' // 是否有更多數據提示的flag,這一行可以無視 let param = (type === 4) ? obj : this.param this.$urlRequest(this.$baseUrl.test, param, 'post').then(res => { if (res.data.success) { if (type !== 3) { this.swipeList = res.data.data.content if (type === 2) { uni.stopPullDownRefresh() } } else { this.swipeList = this.swipeList.concat(res.data.data.content) } this.pagMsg = res.data.data this.more = (this.pagMsg.last || this.pagMsg.totalPage === 0) ? 'noMore' : 'more' //可無視 } else { uni.showToast({ icon: 'none', title: res.data.msg, duration: 1500 }); } }) },