uni-app 返回(后退)上一页并刷新(左上角返回按钮、侧滑后退)

说明

在复杂情况中,返回(后退)上一页并刷新,用下面的方法无法实现:

此时,可以考虑用 onShow() 方法

onShow

页面生命周期函数,官方文档:

https://uniapp.dcloud.net.cn/tutorial/page#lifecycle

作用

监听页面显示,页面 每次出现在屏幕上都触发,包括从下级页面点返回露出当前页面

应用场景

将刷新代码放在该方法中

例子

刷新可能分多种情况:

  • 从 【首页】 打开 【添加页面】,添加后返回 【首页】,此时是刷新全部数据
  • 从 【首页】 打开 【修改页面】,修改后返回 【首页】,此时只需刷新 一部分数据

首页

在【首页】中,通过 uni.getStorageSync() 取出 【刷新类型】,根据【刷新类型】发送ajax请求
在

onShow(){
    const index_ajax_type = uni.getStorageSync('index_ajax_type')
    uni.setStorageSync('index_ajax_type', "")
    // console.log("index_ajax_type:",index_ajax_type)
    if(index_ajax_type == "update_notes_notetypes"){ // 添加后刷新
        this.getNotes()
        this.getNoteTypesOnly()
    }else if(index_ajax_type == "update_notetypes"){ // 修改后刷新
        this.getNoteTypesOnly()
    }else{ // 默认是下拉刷新,也就是全部刷新
        setTimeout( () => {
            uni.startPullDownRefresh()
        },100)
    }

},

添加页面

在【添加页面】中,通过 uni.setStorageSync() 方法,将【刷新类型】存起来

onBackPress:function(event){
    // 点击后退按钮,此时最多只是添加分类,所以只更新分类即可
    uni.setStorageSync('index_ajax_type', "update_notetypes")
    return false;
},

修改页面

在【修改页面】中,通过 uni.setStorageSync() 方法,将【刷新类型】存起来

onBackPress:function(event){
    // 点击后退按钮,此时最多只是添加分类,所以只更新分类即可
    uni.setStorageSync('index_ajax_type', "update_notetypes")
    return false;
},