一、uniapp生命周期(包含uniapp应用生命周期<同小程序应用生命周期>、页面生命周期<同小程序页面生命周期>、组件生命周期)
1.uniapp应用生命周期<同小程序应用生命周期>:onLaunch -> onShow -> onHide
在App.vue根应用中执行
<script>
export default {
onLaunch: function() {
console.log('App Launch')
},
onShow: function() {
console.log('App Show')
},
onHide: function() {
console.log('App Hide')
}
}
</script>
<style>
/*每个页面公共css */
</style>
2.页面生命周期<同小程序页面生命周期>:onLoad -> onShow -> onReady -> onHide -> onUnload
3.组件生命周期:(beforeCreate)Created -> (beforeMount)Mounted -> (beforeUpdate)Updated -> (beforeUnmount)Unmounted 、keep-alive
在页面.vue文件中引入使用
<template>
<view class="g-life">
<text>生命周期</text>
</view>
</template>
<script setup>
import { ref,onMounted,onUpdated,onUnmounted } from "vue"
import { onLoad,onShow,onHide,onReady,onUnload } from '@dcloudio/uni-app'
onLoad(()=>{
console.log('life onLoad ');
})
onShow(()=>{
console.log('life onShow ');
})
onReady(()=>{
console.log('life onReady ');
})
// created
// console.log('created >>>');
onMounted(()=>{
console.log('onMounted >>>');
})
onUpdated(()=>{
console.log('onUpdated >>>');
})
onUnmounted(()=>{
console.log('onunmounted >>>');
})
</script>
<style lang="scss">
</style>
二、路由(API)
uni.navigateTo({url:’/pages/detail/detail’})保留当前页面(onHide),跳转到应用内的某个页面,但是不能跳到 tabbar 页面
uni.navigateBack({delta:1})关闭当前页面(onUnload),返回上一页面或多级页面。可通过 getCurrentPages() 获取当前的页面栈,决定需要返回几层。默认1,返回的页面数,如果 delta 大于现有页面数,则返回到首页。
uni.redirectTo({url:’’})关闭当前页面(onUnload),跳转到应用内的某个页面,但是不允许跳转到 tabbar 页面
uni.switchTab({url:’’})跳转到 tabBar 页面,并关闭其他所有非 tabBar 页面,如果调用了 uni.preloadPage(OBJECT) 不会关闭,仅触发生命周期 onHide
uni.reLaunch({url:’’})关闭所有页面,打开到应用内的某个页面,如果调用了 uni.preloadPage(OBJECT) 不会关闭,仅触发生命周期 onHide
uni.preloadPage({url:’’})预加载页面,是一种性能优化技术。被预载的页面,在打开时速度更快。
平台差异说明:
| App-nvue | H5 | 微信小程序 | 支付宝小程序 | 百度小程序 | 抖音小程序、飞书小程序 | QQ小程序 |
|---|---|---|---|---|---|---|
| √(2.7.12+) | √(2.7.12+) | x | x | x | x | x |
路由传参:
url中路径后通过?参数键=参数值传参,如果传多个参数用&分隔
uni.navigateTo({url:’/pages/detail/detail?id=10&age=18’})
onLoad生命周期中通过options来接收参数
onLoad:function(options){}