【mpvue】微信小程序调用switchTab重定向到页面,不会自动刷新,调用page.onLoad()方法没有效果

本文介绍了一种在小程序中实现基金添加后自动跳转至首页并刷新页面的方法,包括使用page.onLoad()和page.onPullDownRefresh()两种方式,确保用户能立即看到最新添加的基金。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、小程序效果演示

(1)点击添加基金按钮,跳转到添加基金的页面,目前该页面(pages/index/main)有两个基金。


(2)在添加基金页面填写基金代码,会跳出弹框是否继续添加基金


(3)点击取消,会自动跳转到首页,显示刚刚添加的基金

2、需求描述,在添加基金页面添加完基金之后,点击showModal提醒框的取消按钮,自动跳转到首页并自动刷新首页,显示出刚刚添加的基金(/pages/index/main)

错误示范
目前我是像下面这样写的,首页不会自动刷新

wx.showModal({
  title: '成功',
  confirmText: '继续',
  content: `${res.code}(${res.name})添加成功,要继续添加基金吗?`,
  success: function (res) {
    if (res.cancel) {
      wx.switchTab({
        url: '/pages/index/main'
      })
    }
  }
})
3、通过page.onLoad()来解决自动刷新的问题
wx.showModal({
  title: '成功',
  confirmText: '继续',
  content: `${res.code}(${res.name})添加成功,要继续添加基金吗?`,
  success: function (res) {
    if (res.cancel) {
      wx.switchTab({
        url: '/pages/index/main',
        success: function (e) { 
          var page = getCurrentPages().pop();
          console.log('page',page)
          if (page == undefined || page == null) return;
          page.onLoad();
        } 
      })
    }
  }
})

只是写上面语句page.onLoad();语句还不会生效,需要到url: '/pages/index/main'对应的index.vue页面中,添加onLoad函数,其中this.getFunds()是我在methods中定义的获取目前添加的所有基金的方法。

onLoad () {
  this.getFunds()
}

这样onload就生效了。

4、通过page.onPullDownRefresh()来解决自动刷新的问题

(1)首先将page.onLoad();改成page.onPullDownRefresh();

wx.showModal({
  title: '成功',
  confirmText: '继续',
  content: `${res.code}(${res.name})添加成功,要继续添加基金吗?`,
  success: function (res) {
    if (res.cancel) {
      wx.switchTab({
        url: '/pages/index/main',
        success: function (e) { 
          var page = getCurrentPages().pop();
          console.log('page',page)
          if (page == undefined || page == null) return;
          page.onPullDownRefresh();
        } 
      })
    }
  }
})

(2)再在pages/index/index.vue文件中添加上onPullDownRefresh,其中this.getFunds()是我在methods中定义的获取目前添加的所有基金的方法。

<script>
export default {
  onPullDownRefresh () {
	this.getFunds()
  }
}
</script>

(3)在pages/index/main.json中添加代码"enablePullDownRefresh":true,设置允许下拉刷新

{
  "enablePullDownRefresh":true
}

这样添加完基金,返回到显示基金的页面,就会显示刚刚添加的基金了。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

喵宁一

点赞是最好的赞赏~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值