---
name: Page Lifecycle
description: Page and application lifecycle hooks
---
# Page Lifecycle
## Application Lifecycle
In `App.vue`:
```javascript
export default {
globalData: {
userInfo: null,
theme: 'light'
},
onLaunch(options) {
// App launched (only once)
console.log('App launched', options)
this.checkUpdate()
},
onShow(options) {
// App shown/foreground
console.log('App shown', options)
},
onHide() {
// App hidden/background
console.log('App hidden')
},
onError(msg) {
// Global error handler
console.error('App error:', msg)
},
onUnhandledRejection(err) {
// Unhandled promise rejection
console.error('Unhandled rejection:', err)
},
onPageNotFound(res) {
// 404 page not found
console.error('Page not found:', res.path)
uni.redirectTo({
url: '/pages/404/404'
})
},
methods: {
checkUpdate() {
// Check for app updates
const updateManager = uni.getUpdateManager()
updateManager.onCheckForUpdate((res) => {
if (res.hasUpdate) {
console.log('New version available')
}
})
}
}
}
```
## Page Lifecycle
```vue
```
## Component Lifecycle (Vue 2)
```vue
```
## Component Lifecycle (Vue 3)
```vue
```
## Lifecycle Comparison
| Scenario | UniApp Page | Vue Component |
|----------|-------------|---------------|
| Initial load | onLoad | created |
| DOM ready | onReady | mounted |
| Page show | onShow | - |
| Page hide | onHide | - |
| Page destroy | onUnload | destroyed/unmounted |
| Data refresh | onPullDownRefresh | - |
| Infinite scroll | onReachBottom | - |
| Scroll position | onPageScroll | - |
## App Update Manager
```javascript
// In App.vue onLaunch
onLaunch() {
const updateManager = uni.getUpdateManager()
updateManager.onCheckForUpdate((res) => {
console.log('Has update:', res.hasUpdate)
})
updateManager.onUpdateReady(() => {
uni.showModal({
title: 'Update Ready',
content: 'New version downloaded. Restart to apply?',
success: (res) => {
if (res.confirm) {
updateManager.applyUpdate()
}
}
})
})
updateManager.onUpdateFailed(() => {
console.error('Update failed')
})
}
```
## Best Practices
### Data Loading Pattern
```javascript
export default {
data() {
return {
loading: false,
error: null,
data: null
}
},
onLoad(options) {
this.fetchData(options.id)
},
onPullDownRefresh() {
this.fetchData(this.id).finally(() => {
uni.stopPullDownRefresh()
})
},
methods: {
async fetchData(id) {
this.loading = true
this.error = null
try {
this.data = await api.getDetail(id)
} catch (err) {
this.error = err.message
} finally {
this.loading = false
}
}
}
}
```
### Scroll Performance
```javascript
export default {
data() {
return {
scrollTop: 0,
showBackTop: false
}
},
// Throttle scroll events
onPageScroll: throttle(function(e) {
this.scrollTop = e.scrollTop
this.showBackTop = e.scrollTop > 500
}, 200),
methods: {
scrollToTop() {
uni.pageScrollTo({
scrollTop: 0,
duration: 300
})
}
}
}
```